如何使用JFileChooser保存txt文件?

时间:2012-12-16 20:44:35

标签: java swing file 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的项目文件夹内生成的txt文件中写入EncryptedMessage.txt的数据。

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

2 个答案:

答案 0 :(得分: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;
   }
}

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

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

   PrintWriter file = 
        new PrintWriter(new File(saveLocation, "EncryptedMessage.txt"));
   ...
}

答案 1 :(得分:0)

像这样?

PrintWriter file = new PrintWriter(new File(filePathChosenByUser + "EncryptedMessage.txt"));
相关问题