java 如何使用 JFileChooser 保存 txt 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13905298/
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
How to save a txt file using JFileChooser?
提问by user1111726
Given this method :
鉴于这种方法:
public void OutputWrite (BigInteger[] EncryptCodes) throws FileNotFoundException{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.showSaveDialog(null);
String path = chooser.getSelectedFile().getAbsolutePath();
PrintWriter file = new PrintWriter(new File(path+"EncryptedMessage.txt"));
for (int i = 0; i <EncryptCodes.length; i++) {
file.write(EncryptCodes[i]+ " \r\n");
}
file.close();
}
Ignoring the variable names, what this method does is writes data of EncryptCodes
in the txt file generated inside the project folder called EncryptedMessage.txt
.
忽略变量名,这个方法的作用是EncryptCodes
在名为 .txt 的项目文件夹内生成的 txt 文件中写入数据EncryptedMessage.txt
。
What I need is a method to save that txt file instead of in the project folder , to be saved in a location specified by the user during running (Opens a Save As Dialog Box). I think it can be done by JFilechooser, but I can't get it to work.
我需要的是一种方法来保存该 txt 文件而不是项目文件夹中,在运行期间保存在用户指定的位置(打开另存为对话框)。我认为它可以由 JFilechooser 完成,但我无法让它工作。
回答by Reimeus
You could add a separate method for getting the save location like so:
您可以添加一个单独的方法来获取保存位置,如下所示:
private File getSaveLocation() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = chooser.showSaveDialog(this);
if (result == chooser.APPROVE_OPTION) {
return chooser.getSelectedFile();
} else {
return null;
}
}
and then use the result as an argument to the overloaded File
constructor that takes a parent/directory argument:
然后将结果用作重载File
构造函数的参数,该构造函数采用父/目录参数:
public void writeOutput(File saveLocation, BigInteger[] EncryptCodes)
throws FileNotFoundException {
PrintWriter file =
new PrintWriter(new File(saveLocation, "EncryptedMessage.txt"));
...
}
回答by Theolodis
like this?
像这样?
PrintWriter file = new PrintWriter(new File(filePathChosenByUser + "EncryptedMessage.txt"));