save file with JFileChooser save dialog - java

I have written a Java program that opens all kind of files with a JFileChooser. Then I want to save it in another directory with the JFileChooser save dialog, but it only saves an empty file. What can I do for saving part?
Thanks.

JFileChooser just returns the File object, you'll have to open a FileWriter and actually write the contents to it.
E.g.
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(contents);
// etc...
}
Edit:
Assuming that you simply have a source file and destination file and want to copy the contents between the two, I'd recommend using something like FileUtils from Apache's Commons IO to do the heavy lifting.
E.g.
FileUtils.copy(source, dest);
Done!

Just in addition to Kris' answer - I guess, you didn't read the contents of the file yet. Basically you have to do the following to copy a file with java and using JFileChooser:
Select the source file with the FileChooser. This returns a File object, more or less a wrapper class for the file's filename
Use a FileReader with the File to get the contents. Store it in a String or a byte array or something else
Select the target file with the FileChooser. This again returns a File object
Use a FileWriter with the target File to store the String or byte array from above to that file.
The File Open Dialog does not read the contents of the file into memory - it just returns an object, that represents the file.

Something like..
File file = fc.getSelectedFile();
String textToSave = mainTextPane.getText();
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter(file));
writer.write(textToSave);
JOptionPane.showMessageDialog(this, "Message saved. (" + file.getName()+")",
"ImPhil HTML Editer - Page Saved",
JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{ }

Related

Java Buffered Writer to publically accessible location

I am trying to change a program I wrote a while ago. Currently the program handles a few BufferedReader and BufferedWriters with some logic built in. Let me explain how it used to work.
Class used to upload a file:
public void getFile(){//Used to upload the ACH file.
while(uploadApproval==false){//While upload approval has not been given..
JFileChooser chooser = new JFileChooser();//Creates a new object of the JFileChooser class.
uploadFile = chooser;//Saves the upload file variable as the chooser response.
FileNameExtensionFilter filter = new FileNameExtensionFilter("ACH Files", "ach");
//Sets the allowed file formats for upload.
chooser.setFileFilter(filter);//Activates the created file filter.
chooser.setDialogTitle("Please choose ACH file to upload");//Sets the title bar text.
//Completes once the user clicks ok.
int returnVal = chooser.showOpenDialog(chooser);//
if(returnVal == JFileChooser.APPROVE_OPTION){
uploadApproval=true;
}else{
System.exit(0);
}
}
}
Class used to set directory
public void setDirectory(){//Used to set the directory.
while(saveApproval==false){//While the user does not have approval of the save location..
JFileChooser chooser2 = new JFileChooser();//Creates a new JFileChooser object.
saveFile = chooser2;//Sets the save file location to chooser2.
chooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//User is only able to scan for
//directories.
//Completes once the user clicks okay.
int returnValue2 = chooser2.showDialog(chooser2, "Directory to save");
if(returnValue2 == JFileChooser.APPROVE_OPTION){
saveApproval=true;
}else{
System.exit(0);
}
}
}
Then later I begin the actual buffered reader/writer process which involves a lot of logic here:
location = "//NachaOutput"+randomNumber+".ACH";
try{
String sCurrentLine;//String representing the current line.
//Pulls the uploaded file.
br = new BufferedReader(new FileReader(NachaMain.uploadFile.getSelectedFile()));
bw = new BufferedWriter(new FileWriter(NachaMain.saveFile.getSelectedFile()+location));
Now here is what I need to do. I have been asked to remove the screen where the user selects the directory from the beginning. Instead, the user will select the save directory in the end of the process.
This means that the "SetDirectory" method won't be called at all, therefore this line of code:
bw = new BufferedWriter(new FileWriter(NachaMain.saveFile.getSelectedFile()+location));
obviously won't work. I need to find some way to replace that file writer location with a generic location that would be the same for all users regardless of their setup. Something along the lines of documents.
I tried doing this:
bw = new BufferedWriter(new FileWriter("Libraries\\Documents"+location));
but got an exception about an invalid path.
So please help me out and let me know a good path that I could save the file to automatically. That saved file will basically be a "dummy" file. Later in the end of the program I will copy that dummy file to the location the user specifies then delete it, so the location really doesn't matter too much.
Thanks in advance!
You could create a temporary file using File.createTempFile(). It might make cleanup easier if you called deleteOnExit() for the created temporary file.

BufferedWriter is not writing text to text file

I have a BufferedWriter which is being used to write to a file which has just been created in the given directory, however, for some reason it is not writing the text that it reads from another file, here is my code:
private static final String tempFileDir = System.getProperty("user.dir") + "/TempATM.txt";
File tempFile = new File(tempFileDir); //Create temporary file to write new info to
File toRenameTo = new File("VirtualATM.txt"); //filename to rename temp file to
if (!tempFile.exists() && !tempFile.isDirectory()) {
tempFile.createNewFile(); //Create temp file if it doesn't already exist.
}
FileOutputStream fos = new FileOutputStream(tempFile, true); //For writing new balance
Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));//For writing new balance
String newLineRead = null;
FileReader fileReader = new FileReader("VirtualATM.txt");//for reading from file
BufferedReader newBufferedReader = new BufferedReader(fileReader);//for reading from file
while((newLineRead = newBufferedReader.readLine()) != null){
if(!newLineRead.contains(cardNumberStr)){
bw.append(newLineRead); //If the line does not contain user entered card number, write line to new file.
((BufferedWriter) bw).newLine();
}else if(newLineRead.contains(cardNumberStr)){
bw.append(newAccountDetails); //Write updated account details if the line read contains users account number
((BufferedWriter) bw).newLine();
}
}
File toDeleteFile = new File("dirToWriteFile"); //File path to delete the file.
if(!toDeleteFile.delete()){
JOptionPane.showMessageDialog(null, "FATAL ERROR! Could not delete VirtualATM.txt", "Error", JOptionPane.ERROR_MESSAGE); // for if there is an error when deleting file
}
if(!file.renameTo(toRenameTo)){
JOptionPane.showMessageDialog(null, "FATAL ERROR! Could not rename the file to VirtualATM.txt", "Error", JOptionPane.ERROR_MESSAGE);//for if there is an error renaming file
}
Edit:
I am also having trouble deleting and renaming the text file, could any suggest what may be causing this problem, what SecurityExceptions etc. may be preventing Java from deleting and renaming a text file (.txt) on Windows 8.1?
You need to either flush the buffer post writing the data to buffer like
bw.flush();
or close the writer like
bw.close();//handle exception if you are not using AutoCloseable feature.
You must either flush the buffer to the disk after writing the data using:
bw.flush();
or / and if you have finished writing the data, you must always close the writer which will automatically flush the data to the disk before closing using:
bw.close();
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty

Set default saving extension with JFileChooser

I'm trying to save a file using JFileChooser. However, I seem to be having some trouble with it. Here's my code:
if (e.getSource() == saveMenu) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
FileNameExtensionFilter xmlFilter = new FileNameExtensionFilter("xml files (*.xml)", "xml");
// add filters
chooser.addChoosableFileFilter(xmlFilter);
chooser.setFileFilter(xmlFilter);
int result = chooser.showSaveDialog(Simulation.this);
if (result == chooser.APPROVE_OPTION) {
writeToXML(chooser.getSelectedFile());
}
}
This doesn't force the file to have a .xml extension, so I've tried to use the following code to force the file to be saved with the extension .xml
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter xmlWriter = null;
try {
xmlWriter = new XMLWriter(new OutputStreamWriter(
new FileOutputStream(f+".xml"), "UTF8"),
format);
However, with this I can't prevent the user from writing xpto.xml in the JFileChooser and if they do that, the file will have "two extensions": it will be a file named xpto.xml.xml
So my questions are:
How can I make the JFileChooser save an xml file by default?
If the user inserts a file name like xpto.xml, how can I save it as xpto.xml and not xpto.xml.xml?
As you've noticed, JFileChooser doesn't enforce the FileFilter on a save. It will grey-out the existing non-XML file in the dialog it displays, but that's it. To enforce the filename, you have to do all the work. (This isn't just a matter of JFileChooser sucking -- it's a complex problem to deal with. Your might want your users to be able to name their files xml.xml.xml.xml.)
In your case, I recommend using FilenameUtils from Commons IO:
File file = chooser.getSelectedFile();
if (FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("xml")) {
// filename is OK as-is
} else {
file = new File(file.toString() + ".xml"); // append .xml if "foo.jpg.xml" is OK
file = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName())+".xml"); // ALTERNATIVELY: remove the extension (if any) and replace it with ".xml"
}
There's also some ideas for what to do if you want multiple types in the save dialog here: How to save file using JFileChooser?
Just to make things clear as to how to use the JFileChooser to save files.
//set it to be a save dialog
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
//set a default filename (this is where you default extension first comes in)
chooser.setSelectedFile(new File("myfile.xml"));
//Set an extension filter, so the user sees other XML files
chooser.setFileFilter(new FileNameExtensionFilter("xml file","xml"));
now the user was encouraged to save the item as an xml file in this example, but they may not have actually set it.
if(chooser.showSaveDialog(this) == jFileChooser.APPROVE_OPTION) {
String filename = chooser.getSelectedFile().toString();
if (!filename .endsWith(".xml"))
filename += ".xml";
//DO something with filename
}
This is the most simple case, if you have multiple possible file formats, then you should catch the selected filter, verify THAT extension, and also save the file according to the selected format. but if you are doing that, you are probably an advanced java programmer and not utilizing this post.
How about something like this:
else if (e.getSource() == saveMenu) {
int returnVal = chooser.showSaveDialog(Simulator.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String fname = file.getAbsolutePath();
if(!fname.endsWith(".xml") ) {
file = new File(fname + ".xml");
if(!file.createNewFile()) {
/*check with user??*/
}
You should try this:
if(!file.getName().contains(".")) file = new File(file.toString() + ".xml");
You should try this. I did this and it worked.
FileOutputStream fileOut = new FileOutputStream(file1+".xml");
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");

How to save the text file in a path given by JFileChooser?

I need to save a text File which is already created in a particular path given by JFileChooser. What I do basically to save is:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
System.out.print(chooser.getCurrentDirectory());
// Don't know how to do it
}
How to save the text file in a path given by JFileChooser?
You want to add the following after if statement:
File file = chooser.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(foo);
where foo is your content.
EDIT:
As you want to write a text file, I'd recommend the following:
PrintWriter out = new PrintWriter(file);
BufferedReader in = new BufferedReader(new FileReader(original));
while (true)
{
String line = in.nextLine();
if (line == null)
break;
out.println(line);
}
out.close();
where original is the file containing data you want to write.
create a new File object with the path and name for the file
File file = new File(String pathname)
Try this:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
FileWriter out=new FileWriter(chooser.getSelectedFile());
try {
out.write("insert text file contents here");
}
finally {
out.close();
}
}
// ...
You'll need the filename you want to save under in addition to the directory provided by chooser.getCurrentDirectory(), but that should do what you need it to. Of course, you'll need to write the save method that actually writes to the stream, too, but that's up to you. :)
EDIT: There's a much method to use, chooser.getSelectedFile(), that should be used here, per another answer in the thread. Updated to use that method.
EDIT: Since OP specified the file being written is a text file, I've added code to write the contents of the file. Of course, you'll need to replace "insert text file contents here" with the actual file contents to write.

set directory to a path in a file

I just want to set the directory to a path I have written in a file before.
Therefore I used :
fileChooser.setCurrentDirectory(new File("path.txt"));
and in path.txt the path is given. But unfortunately this does not work out and I wonder why :P.
I think I got it all wrong with the setCurrentDic..
setCurrentDirectory takes a file representing a directory as parameter. Not a text file where a path is written.
To do what you want, you have to read the file "path.txt", create a File object with the contents that you just read, and pass this file to setCurrentDirectory :
String pathWrittenInTextFile = readFileAsString(new File("path.txt"));
File theDirectory = new File(pathWrittenInTextFile);
fileChooser.setCurrentDirectory(theDirectory);
You have to read the contents of path.txt. Thea easiest way is through commons-io:
String fileContents = IOUtils.toString(new FileInputStream("path.txt"));
File dir = new File(fileContents);
You can also use FileUtils.readFileToString(..)
JFileChooser chooser = new JFileChooser();
try {
// Create a File object containing the canonical path of the
// desired directory
File f = new File(new File(".").getCanonicalPath());
// Set the current directory
chooser.setCurrentDirectory(f);
} catch (IOException e) {
}

Categories