私がやろうとしているのは、単にユーザーにテキストファイルを保存するディレクトリを選択させることです。問題は、デスクトップに作成しているフォルダを選択しようとしているのですが、JFileChooserでフォルダを選択し、持っているコードに作業はまだフォルダの外にあり、デスクトップに保存されています。なぜですか?私が何かを学ぶかもしれないので、誰かが私が間違ったことを説明してもらえますか?
public class TextFileSaver {
String filePath;//Used in the setPath and getPath methods
String filename = File.separator+"tmp"; //Used for the JFileChoosers directory
public TextFileSaver(){
//Get our file saver to the screen
JFileChooser fc = new JFileChooser(new File(filename));
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //Only able to select directiories
// Show open dialog; this method does not return until the dialog is closed
fc.showSaveDialog(null);
File selectedLocation = fc.getCurrentDirectory(); //Gets the selected Location
//Sets the path of the file so we can read from it.
setPath(selectedLocation.getAbsolutePath());
FileName();
try {
SaveFile(filePath);
}
catch (IOException ex) {
Logger.getLogger(TextFileSaver.class.getName()).log(Level.SEVERE, null, ex);
//Show a message dialog
JOptionPane.showMessageDialog(null, "The file could not be saved, Please try again.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public void setPath(String Path){
filePath = Path;
}
public String getPath(){
return filePath;
}
private void FileName(){
String name = JOptionPane.showInputDialog
("What name do you want to give the file?");
//Temporary code bellow will change to StringBuilder here.
filePath = filePath + "/" + name + ".txt";
}
private void SaveFile(String Path) throws IOException{
System.out.println(Path);
//The outStream that we will use to write to the text file the user is creating.
PrintWriter outStream = new PrintWriter(new BufferedWriter(new FileWriter(Path)));
outStream.println("Test text!");
outStream.close();
}
}
すべてのメソッドはコンストラクターを介して実行されます。したがって、コードは段階的に発生します。