0

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

所有的方法都是通过构造函数执行的。所以代码是一步一步发生的。。

4

1 回答 1

3

使用getSelectedFile()而不是getCurrentDirectory(),你应该在某处附加你的文件路径。

于 2012-03-06T18:25:50.720 回答