如何使用JFileChooser保存txt文件?

use*_*726 1 java swing jfilechooser file

鉴于此方法:

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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

Rei*_*eus 5

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

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;
   }
}
Run Code Online (Sandbox Code Playgroud)

然后使用结果作为File带有父/目录参数的重载构造函数的参数:

public void writeOutput(File saveLocation, BigInteger[] EncryptCodes)
                 throws FileNotFoundException {

   PrintWriter file = 
        new PrintWriter(new File(saveLocation, "EncryptedMessage.txt"));
   ...
}
Run Code Online (Sandbox Code Playgroud)