如何使用JFileChooser保存txt文件? [英] How to save a txt file using JFileChooser?
问题描述
给出此方法:
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();
}
忽略变量名,此方法的作用是将EncryptCodes
的数据写入在名为EncryptedMessage.txt
的项目文件夹中生成的txt文件中.
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
.
我需要的是一种保存该txt文件而不是保存在项目文件夹中的方法,以将其保存在用户在运行期间指定的位置(打开另存为"对话框).我认为这可以通过JFilechooser完成,但我无法使其正常工作.
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.
推荐答案
您可以添加一个单独的方法来获取保存位置,如下所示:
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;
}
}
,然后将结果用作带有父/目录参数的重载File
构造函数的参数:
and then use the result as an argument to the overloaded File
constructor that takes a parent/directory argument:
public void writeOutput(File saveLocation, BigInteger[] EncryptCodes)
throws FileNotFoundException {
PrintWriter file =
new PrintWriter(new File(saveLocation, "EncryptedMessage.txt"));
...
}
这篇关于如何使用JFileChooser保存txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!