javadirectorysavefilewriter

How to set the directory when saving file with filewriter in java?


Hi I'm using NetBeans for more easy-to-use GUI.

I'm trying to save a txt file which I get the name from the user, using the FileWriter, (not using serializable)

I think I could set the saving location of the file using the Serializable (I'm not sure)

but, my code kinda looks dirty if I use Serializable and it causes some error. (I use 2 classes)

Anyway, Is there a way to set the directory when saving the txt file with the FileWriter?

This is my code, for saving files.

    public boolean save() {
    try {
        File dir = new File("C:\\Users\\JSK\\Desktop\\BOARD\\data");

        String str = Title_field.getText() + ".txt";
        CheckFile(str);
        CheckCbox();
        area.append("\n Written at :" + date_format.format(now.getTime()));
        FileWriter fw = new FileWriter(str);
        fw.write(area.getText());
        fw.close();
        JOptionPane.showMessageDialog(this, "Successfully Written");
        this.setVisible(false);
        Title_field.setEditable(false);
        area.setEditable(false);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(this, "You Must Create A File First!", "File Missing", JOptionPane.ERROR_MESSAGE);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(this, "I/O ERROR", "Failed to save the file", JOptionPane.ERROR_MESSAGE);
    } catch (FileExistException ex) {
        JOptionPane.showMessageDialog(this, "File Already Exists, Please Change the title", "ERROR", JOptionPane.ERROR_MESSAGE);
        area.setText("");
        return false;
    } catch (CheckboxSelectionException ex) {
        JOptionPane.showMessageDialog(this, "You must select at least one location", "ERROR", JOptionPane.ERROR_MESSAGE);
        Title_field.setText("");
        area.setText("");
        return false;
    }

    return true;
}    

dir means the directory where I want to save it, but it actually saves inside C:\Users\JSK\Desktop\BOARD


Solution

  • Instead of this line:

    FileWriter fw = new FileWriter(str);
    

    Try this:

    FileWriter fw = new FileWriter(new File(dir, str));