Java 使用 JFileChooser 保存对话框保存文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2377703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
save file with JFileChooser save dialog
提问by samuel
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?
我编写了一个 Java 程序,可以使用 JFileChooser 打开所有类型的文件。然后我想用 JFileChooser 保存对话框将它保存在另一个目录中,但它只保存一个空文件。我可以做什么来保存零件?
Thanks.
谢谢。
回答by Kris
JFileChooser just returns the File object, you'll have to open a FileWriter and actually write the contents to it.
JFileChooser 只返回 File 对象,您必须打开 FileWriter 并将内容实际写入其中。
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 FileUtilsfrom Apache's Commons IOto do the heavy lifting.
假设您只有一个源文件和目标文件,并且想要在两者之间复制内容,我建议您使用Apache 的Commons IO 中的FileUtils 之类的东西来完成繁重的工作。
E.g.
例如
FileUtils.copy(source, dest);
Done!
完毕!
回答by Andreas Dolk
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:
除了Kris 的回答之外- 我想,您还没有阅读文件的内容。基本上,您必须执行以下操作才能使用 java 和使用 JFileChooser 复制文件:
- Select the sourcefile 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 targetfile 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.
- 使用 FileChooser选择源文件。这将返回一个 File 对象,或多或少是文件文件名的包装类
- 使用 FileReader 和 File 来获取内容。将它存储在字符串或字节数组或其他东西中
- 使用 FileChooser选择目标文件。这再次返回一个 File 对象
- 使用带有目标文件的 FileWriter 将字符串或字节数组从上面存储到该文件。
The File Open Dialog does not read the contents of the file into memory - it just returns an object, that represents the file.
File Open Dialog 不会将文件的内容读入内存——它只是返回一个代表文件的对象。
回答by Phil
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)
{ }