user2445678
user2445678

Reputation: 1

How to save files in Java using variables in absolute path?

My problem is saving documents in Netbeans. I created a program using Java in Netbeans. At first you register (at the click on register button a new user Map is created with the name of the user), then you login with your user name and your password. When you are logged in, the program displays a new window where you can create documents. You can write text in TextArea. Then when you're finished with writing your text you click on Save button and the text you've written saves in a document named after the text you've given in a jTextField. So for every different login the absolute path changes.

This is my code in submit button:

//ccc is the name of user map
String ccc = LogIn.uporabnik1;
try{
    FileWriter writer = new FileWriter("C:\\Users\\ALEKS\\Documents\\NetBeansProjects\\EasyEdit\\"+ccc+"\\"+FileName+".txt");
    BufferedWriter bw = new BufferedWriter (writer);
    jTextArea1.write(bw);
    bw.close();
    jTextArea1.setText("");
    jTextArea1.requestFocus();
    writer.close();
}
catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}

Upvotes: 0

Views: 3392

Answers (1)

assylias
assylias

Reputation: 328598

It looks like there is a typo with an extra space in your path.

Note that as an alternative, if you use Java 7+, you can also use the Paths utility class to generate paths without having to deal with os specific separators (\\ or /):

Path path = Paths.get("C:/Users/ALEKS/Documents/NetBeansProjects/EasyEdit/" 
                     + ccc + "/" + FileName + ".txt");

And to write a string to a file:

String text = jTextArea1.getText();
Files.write(path, text.getBytes("UTF-8"));

That makes your code shorter and you don't have to manually create and close the streams.

Finally, for long-ish operations, you should not use the GUI thread but use a background thread instead or you application will become unresponsive as the save operation is in progress.

Upvotes: 2

Related Questions