问题
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