Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java WriteFile can't see contents

Tags:

java

io

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?

like image 653
Mladen P Avatar asked Jun 05 '26 18:06

Mladen P


1 Answers

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();
like image 54
Adriano Repetti Avatar answered Jun 08 '26 08:06

Adriano Repetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!