How to save a txt file using JFileChooser?

▼魔方 西西 提交于 2019-12-10 11:45:42

问题


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.

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.


回答1:


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:

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

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



回答2:


like this?

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


来源:https://stackoverflow.com/questions/13905298/how-to-save-a-txt-file-using-jfilechooser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!