如何使用JFileChooser保存txt文件?

鉴于此方法:

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(); } 

忽略变量名称,此方法的作用是在名为EncryptedMessage.txt的项目文件夹内生成的txt文件中写入EncryptCodes数据。

我需要的是一种保存该txt文件而不是项目文件夹的方法,以便在运行期间保存在用户指定的位置(打开另存为对话框)。 我认为它可以由JFilechooser完成,但我无法让它工作。

您可以添加一个单独的方法来获取保存位置,如下所示:

 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构造函数的参数:

 public void writeOutput(File saveLocation, BigInteger[] EncryptCodes) throws FileNotFoundException { PrintWriter file = new PrintWriter(new File(saveLocation, "EncryptedMessage.txt")); ... } 

像这样?

 PrintWriter file = new PrintWriter(new File(filePathChosenByUser + "EncryptedMessage.txt"));