save file with JFileChooser save dialog

佐手、 提交于 2019-11-29 23:36:26

问题


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.


回答1:


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!




回答2:


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:

  1. Select the source file with the FileChooser. This returns a File object, more or less a wrapper class for the file's filename
  2. Use a FileReader with the File to get the contents. Store it in a String or a byte array or something else
  3. Select the target file with the FileChooser. This again returns a File object
  4. 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.




回答3:


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)
{ }


来源:https://stackoverflow.com/questions/2377703/save-file-with-jfilechooser-save-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!