我试图做的只是让用户选择一个目录来保存文本文件,问题是我试图选择一个在我的桌面上创建的文件夹,但是当我使用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();
}
}


所有方法都是通过构造函数执行的。因此,代码逐步发生。

最佳答案

使用getSelectedFile()而不是getCurrentDirectory(),而且,您应该将filePath附加到某个位置。

10-06 10:39
查看更多