I use DirectoryChooser to choose where the file will be save
Gson gson = new GsonBuilder().setPrettyPrinting().create();
DirectoryChooser directoryChooser = new DirectoryChooser();
Stage stage = (Stage) anchorPane.getScene().getWindow();
File selectedDirectory = directoryChooser.showDialog(stage);
File file = null;
if(selectedDirectory!=null){
file = new File(selectedDirectory.getAbsolutePath()+"\\"+"test"+".txt");
try(FileWriter fileWriter = new FileWriter(file)){
gson.toJson(data,fileWriter);
}catch (IOException e){
System.out.println("IO Error");
}
}
It works well, but I'd like to be able to write the file name, like this:
but instead I can only choose the path folder:
How can I change the code to get the window like in the first picture?
Related
I am working on an e-commerce app using JavaFX, I am using SQL server 2014 and I was unable to retrieve image from database. I am using a for loop to add all the values of the database on a grid pane. The image was supposed to be at the center of the grid pane with the product name and price at the bottom. I get a java.lang.NullPointerException every time I tried it. could any one please help me?
BorderPane background[]= new BorderPane[13];
Label productName[]= new Label[13];
Label priceLable[]= new Label[13];
Image image;
ImageView imageView;
for (int i = 0; i<=12;i++){
background[i]=new BorderPane();
background[i].setStyle("-fx-background-color: rgb(216, 216, 216)");
background[i].setPrefHeight(300);
background[i].setPrefWidth(250);
try {
String query = "select pname,price,manufacturer,pimg from Adulis_product where pid=?";
pst = con.prepareStatement(query);
pst.setInt(1, adp.getProduct_id());
rs = pst.executeQuery();
while (rs.next()) {
productName[i]=new Label(rs.getString("pname")+" - "+rs.getString("manufacturer"));
productName[i].setStyle("-fx-text-fill: #282828");
productName[i].setFont(Font.font(" sans-serif", FontWeight.EXTRA_BOLD,14));
priceLable[i]= new Label(rs.getString("price"));
priceLable[i].setStyle("-fx-text-fill: #1da288");
priceLable[i].setFont(Font.font(" sans-serif", FontWeight.EXTRA_BOLD,15));
int finalI2 = i;
InputStream is = rs.getBinaryStream("pimg");
OutputStream os= new FileOutputStream(new File("pic.jpg"));
byte[] content= new byte[1024];
int size=0;
while((size = is.read(content))!=-1){
os.write(content, 0,size);
}
os.close();
is.close();
image = new Image("file:pic"+i+".jpg", 250,300,false,true);
imageView = new ImageView(image);
imageView.setFitHeight(300);
imageView.setFitWidth(250);
VBox prceNmanufactue= new VBox(10);
prceNmanufactue.getChildren().addAll(productName[i],priceLable[i]);
prceNmanufactue.setPadding(new Insets(0,0,0,5));
Image newp= new Image(getClass().getResourceAsStream("New_30px.png"));
ImageView newimv= new ImageView(newp);
background[i].setTop(newimv);
VBox borderElements= new VBox(5);
borderElements.getChildren().addAll(prceNmanufactue,addtocart[i]);
background[i].setBottom(borderElements);
}
} catch (Exception e1) {
System.out.println(e1);
}
You are writing the image data to a file with filename pic.jpg:
InputStream is = rs.getBinaryStream("pimg");
OutputStream os= new FileOutputStream(new File("pic.jpg"));
byte[] content= new byte[1024];
int size=0;
while((size = is.read(content))!=-1){
os.write(content, 0,size);
}
and then trying to read from a file with a different name:
image = new Image("file:pic"+i+".jpg", 250,300,false,true);
So presumably you intended to do
OutputStream os= new FileOutputStream(new File("pic"+i+".jpg"));
Copying all the data to a file just to read it back in is incredibly inefficient. Do you really need the file? Why not just do
InputStream is = rs.getBinaryStream("pimg");
image = new Image(is, 250,300,false,true);
You also don't seem to do anything with this image view, so you need to add it to some pane somewhere.
private void initPlayer() throws MalformedURLException{
File dir = new File("../Railway PRS/Videos");
if (!dir.exists() && dir.isDirectory()){
//System.out.println("Cannot find audio source directory: " + dir);
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("File Not Found");
alert.setHeaderText("Video File Not Found: ");
alert.setContentText("Place the video folder onto the following location: ../Railway/Videos/File.mp4");
alert.showAndWait();
}
final List<MediaPlayer> players = new ArrayList<>();
File folder = new File("../Railway UTS/Videos");
File[] listofFiles = folder.listFiles();
File file;// = null;
for (i = 0; i < listofFiles.length; i++){
file = new File(listofFiles[i].getName());
//Media media = new Media(file.toURI().toURL().toString());
players.add(new MediaPlayer(new Media(file.toURI().toURL().toString())));
}
if (players.isEmpty()) {
//System.out.println("No audio found in " + dir);
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Audio File Not Found");
alert.setHeaderText("Audio File?");
alert.setContentText("Place the videos onto the following location: ../Railway/Videos/File.mp4");
alert.showAndWait();
}
mediaview = new MediaView(players.get(0));
//mediaview1 = new MediaView(players.get(0));
for ( j = 0; j < players.size(); j++){
final MediaPlayer player = players.get(j);
final MediaPlayer nextPlayer = players.get((j + 1) % players.size());
player.setOnEndOfMedia(new Runnable() {
#Override
public void run() {
mediaview.setMediaPlayer(nextPlayer);
nextPlayer.play();
//nextPlayer.setCycleCount(nextPlayer.INDEFINITE);
//player.setCycleCount(MediaPlayer.INDEFINITE);
}
});
}
mediaview.setMediaPlayer(players.get(0));
mediaview.getMediaPlayer().play();
basepane.getChildren().addAll(mediaview);
}
The above code plays the video(playlist) only once. I want it to play the video(playlist) continously. If I set the cyclecount to Indefinite it repeats the first video while playing the second video means we can hear the sound of first video. I want the playlist to play continuously non-stop unless the application is exited.
Just put the following line in the for loop and it will work.It will play the video/videos in cycle.
nameofmediaplayer.seek(DURATION.ZERO);
I am converting a doc file to a pdf file but with my current code it seems that the file is open even after the conversion. I see the pdf file in the output folder but if i try to reupload it tells me that it is opened in another program(which i don't see anywhere).
Code section error:
if (getExt == ".doc")
{
Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
wordDocument = appWord.Documents.Open(DocumentUNCPath.Text);
wordDocument.ExportAsFixedFormat(#"c:\temp\DocTo.pdf", WdExportFormat.wdExportFormatPDF);
}
The full method:
private void btnSubmitStep2_Click(object sender, EventArgs e)
{
string getExt = Path.GetExtension(DocumentUNCPath.Text);
if (getExt == ".doc")
{
Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
wordDocument = appWord.Documents.Open(DocumentUNCPath.Text);
wordDocument.ExportAsFixedFormat(#"c:\temp\DocTo.pdf", WdExportFormat.wdExportFormatPDF);
}
// Frame up the record of submission
using (var dc = new DocMgmtDataContext())
{
DocumentLibrary.Document doc = new DocumentLibrary.Document()
{
LibraryID = (AssignmentListStep2.SelectedItem as Library).ID,
OwnedByUserID = (StudentListStep2.SelectedItem as User).ID,
UploadedByUserID = (StudentListStep2.SelectedItem as User).ID,
UploadDT = DateTime.UtcNow,
ID = Guid.NewGuid()
};
dc.Documents.InsertOnSubmit(doc);
dc.SubmitChanges();
// Copy file into managed storage
doc.StoragePath = FILESTORELOCATION + doc.ID + ".pdf";
File.Copy(DocumentUNCPath.Text, doc.StoragePath);
doc.Pages = CompatiblePdfReader.VerifyAndFixPdfDocument(doc.StoragePath);
dc.SubmitChanges();
}
// Refresh the list of student submissions
UpdateStudentSubmissionGrid();
}
Try closing the document at the end of your sub with wordDocument.Close SaveChanges:=wdDoNotSaveChanges, as ExportAsFixedFormat doesn't close the file for you.
I am currently using TrueZip to add a file to a Zip file that was uploaded to a server via MultiPartFile.
The Problem
Upon appending a file the zip becomes invalid. It can no longer be opened as a zip file.
The Code
Let's start with the relevant code in my upload controller (file is the MultiPartFile):
// Get the file
File dest = null;
TFile zip = null;
try {
// Obtain the file locally, zip, and delete the old
dest = new File(request.getRealPath("") + "/datasource/uploads/" + fixedFileName);
file.transferTo(dest);
// Validate
zip = new TFile(dest);
resp = mls.validateMapLayer(zip);
// Now perform the upload and delete the temp file
FoundryUserDetails userDetails = (FoundryUserDetails) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
UserIdentity ui = userDetails.getUserIdentity();
MapLayer newLayer = new MapLayer();
// generate the prj
mls.generateProjection(resp, dest.getAbsolutePath(), projection);
The method "generateProjection" is where the file is added:
public void generateProjection(UploadMapResponse resp, String fLoc, FoundryCRS proj) throws NoSuchAuthorityCodeException,
FactoryException, IOException {
TFile projFile = new TFile(fLoc, resp.getLayerName() + ".prj");
CoordinateReferenceSystem crs = CRS.decode(proj.getEpsg());
String wkt = crs.toWKT();
TConfig config = TConfig.push();
try {
config.setOutputPreferences(config.getOutputPreferences().set(FsOutputOption.GROW));
TFileOutputStream writer = new TFileOutputStream(projFile);
try {
writer.write(wkt.getBytes());
} finally {
writer.close();
}
} finally {
config.close();
}
}
In order to test if this worked at all I tried it in a simple main:
public static void main(String[] args) {
File f = new File("C:/Data/SierritaDec2011TopoContours.zip");
TFile tf = new TFile(f);
tf.listFiles();
TFile proj = new TFile(f, "test.prj");
TConfig config = TConfig.push();
try {
config.setOutputPreferences(config.getOutputPreferences().set(FsOutputOption.GROW));
TFileOutputStream writer = null;
try {
writer = new TFileOutputStream(proj);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
writer.write("Hello Zip world".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} finally {
// Pop the current configuration off the inheritable thread local
// stack.
config.close();
}
}
Which, of course, works just fine.
The Question
Does anyone have insight into why, in a web server with a MultiPartFile copied to a local file, the TFileOutputStream fails to write properly?
In a long running server app, you may need to add a call to TVFS.sync() or TVFS.umount() in order to sync or umount archive files. In the case of ZIP files, this will trigger to write the Central Directory at the end of the ZIP file, which is required to form a valid ZIP file.
Please check the Javadoc to decide which call is the best for your use case: http://truezip.java.net/apidocs/de/schlichtherle/truezip/file/TVFS.html
Also, please note that calling TFVS.sync() or TVFS.umount() after each append operation will result in a growing Central Directory to be written each time, which results in huge overhead. So it's worth to consider when exactly you need to do this. Generally speaking this is only required when you want a third party to access the ZIP file. A third party is anyone not interacting with the TrueZIP Kernel for accessing the ZIP file.
I am trying to programatically build a list of files in a folder, with certain attributes like file size and modified date.
I can return the file name, but any other attribute throws an error: System.IO.IOException: The filename, directory name, or volume label syntax is incorrect.
What am I missing here?
private void BuildDocList()
{
var files = Directory.GetFiles(Server.MapPath(FilePath));
foreach (var f in files)
{
var file = new FileInfo(FilePath + f);
var fileItem = new ListItem();
// this line works fine
fileItem.Text = file.Name.Split('.')[0] + ", ";
// this line causes the runtime error
fileItem.Text = file.CreationTime.ToShortDateString();
FileList.Items.Add(fileItem);
}
}
You're trying to use the wrong filename for the FileInfo - you're using the unmapped path. You should use something like this:
string directory = Server.MapPath(FilePath);
string[] files = Directory.GetFiles(directory);
foreach (string f in files)
{
FileInfo file = new FileInfo(Path.Combine(directory, f));
// Now the properties should work.