What im trying to do is simply letting the user choose a directory to save a text file to, Problem is im trying to select a folder im creating on my desktop but when i select the folder with the JFileChooser and letting the code i have do the work it's still saved outside the folder and into the desktop.. Why? Can someone please explain what i did wrong so i might learn something..

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();
}
}

All the methods are executed through the constructor.. So the code happends step by step..

有帮助吗?

解决方案

Use getSelectedFile() and not getCurrentDirectory() and also, you should append your filePath somewhere.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top