scarecrow-
scarecrow-

Reputation: 86

opening file using java and appending

I am wondering why nothing is being written to my file. I have the file in my project space, anytime I open it, there is nothing there. I am essentially trying to write to a file, close it, then appened to it again. so on so forth.

public static void writeToFile(String name) throws IOException{

    FileWriter fw = new FileWriter("myFile.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw);
    out.println(name);
    fw.close();
}

in my main I am just calling the method with a random string in the parameter

Upvotes: 1

Views: 39

Answers (2)

Jayanth
Jayanth

Reputation: 6297

This worked for me

FileWriter fWriter;
File mFile = new File("fully qualified file name");
try{
 fWriter = new FileWriter(mFile, true);
 fWriter.write("File content");
 fWriter.flush();
 fWriter.close();
 }catch(Exception e){
      e.printStackTrace();
 }

Upvotes: 1

Sid Savara
Sid Savara

Reputation: 161

Try adding flush() before you close the file. PrintWriter does not have automatic flushing

Upvotes: 1

Related Questions