Mladen P
Mladen P

Reputation: 176

Java WriteFile can't see contents

I want to create a simple text file with some text in it.

import java.io.*;

class TextFileWriter{
public static void writeTextFile(String fileName, String s) {
    FileWriter output = null;
    try {
      output = new FileWriter(fileName);
      BufferedWriter writer = new BufferedWriter(output);
      writer.write(s);

    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      if (output != null) {
        try {
          output.close();
        } catch (IOException e) {
        }
      }
    }

  } 

public static void main(String args[]){
    writeTextFile("myText.txt","some text");
}
}

When i run this code i successfully create the text file but when i open it i don't see the contents ("some text"). What am I doing wrong?

Upvotes: 3

Views: 55

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67080

You're closing underlying FileWriter but actual data are still stored (buffered) in BufferedWriter object. That's the object you have to close:

FileWriter output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.flush(); // Good practice but not required
writer.close();

Upvotes: 5

Related Questions