Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing to a file problem [duplicate]

Tags:

java

file-io

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?

like image 811
JJunior Avatar asked May 14 '26 16:05

JJunior


2 Answers

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.

like image 74
Tore A. Avatar answered May 17 '26 15:05

Tore A.


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

like image 23
Sanjay Manohar Avatar answered May 17 '26 14:05

Sanjay Manohar