简体   繁体   English

如何使用JFileChooser保存txt文件?

[英]How to save a txt file using JFileChooser?

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数据写入在名为EncryptedMessage.txt的项目文件夹内生成的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). 我需要的是一种保存该txt文件而不是保存在项目文件夹中的方法,以将其保存在用户在运行期间指定的位置(打开“另存为”对话框)。 I think it can be done by JFilechooser, but I can't get it to work. 我认为可以通过JFilechooser完成,但是我无法使其正常工作。

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"));
   ...
}

像这样?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM