2

I am using this code to write to a file in java. it has always worked and I am 100% sure its right. But still the file does not get written. I don't even get an error.

import java.io.BufferedWriter;   
import java.io.FileWriter;
import java.io.IOException;

public class writetofile {

    public static void main(String [] args){

        FileWriter fw;

        try {
            fw = new FileWriter("testfile.txt");

            BufferedWriter bw = new BufferedWriter(fw);

            bw.write("this is test");

            bw.write("this is test");
            bw.write("this is test");


        } catch (IOException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Could it be some other problem?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
JJunior
  • 2,831
  • 16
  • 56
  • 66

5 Answers5

8

You are not calling the close() method on the BufferedWriter object. That means the buffers never get flushed. Add bw.close() after your last bw.write() statements.

Tore A.
  • 609
  • 3
  • 5
6

try fw.flush() and fw.close()

Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58
3

You need to flush the buffer and you should close the file as well:

try {
            fw = new FileWriter("/tmp/testfile.txt");
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("this is test");
            bw.write("this is test");
            bw.write("this is test");
            bw.flush();
            fw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Also you should handle the IOException from the actual file writing separately from the file closing so you won't leave the file descriptor opened at the end:

    FileWriter fw = null;
    try {
        fw = new FileWriter("/tmp/testfile.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("this is test");
        bw.write("this is test");
        bw.write("this is test");
        bw.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fw != null) {
                fw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
fikovnik
  • 3,473
  • 3
  • 28
  • 29
  • 1
    +1, the only as far who mentions closing in `finally`, the right way. Note that `flush()` is still unnecessary as `close()` implicitly does that. But that doesn't hurt. Not closing in `finally` may hurt more in exceptional cases. – BalusC Aug 18 '10 at 13:37
2

Make sure you call bw.close() before your method exits. If the buffer doesn't get flushed your file wont get written.

Lazarus
  • 41,906
  • 4
  • 43
  • 54
1

Try closing the stream with sw.close() or the data may still be cached and not actually written to disk.

KeatsPeeks
  • 19,126
  • 5
  • 52
  • 83