OtagoHarbour
OtagoHarbour

Reputation: 4183

out.write runs several times but resulting file is empty

I am developing in Java SE on NetBeans 7.3.1 on Windows 7.

I am trying to write a set on numbers, one on each line, to an ASCII text file.

            FileWriter fstream = new FileWriter(outputFileName, false); //false tells to not append data.
            BufferedWriter out = new BufferedWriter(fstream);
            for (int i=0; i<numBins; ++i){
                String str=Integer.toString(hist[i]);
                str.concat("\n");
                out.write(str);
            }
            br.close();

numBins is 6 and the program runs through without any errors. I check tih the debugger and

 out.write(str); 

is called 6 times. hist[i] are small integral numbers. For some reason, the resulting file is empty and of zero size.

Upvotes: 0

Views: 134

Answers (2)

Juned Ahsan
Juned Ahsan

Reputation: 68715

You need to call close method on your BufferedWriter object to flush the contents to file:

   FileWriter fstream = new FileWriter(outputFileName, false); //false tells to not append data.
            BufferedWriter out = new BufferedWriter(fstream);
            for (int i=0; i<numBins; ++i){
                String str=Integer.toString(hist[i]);
                str.concat("\n");
                out.write(str);
            }
           // add this also
           out.close();

Upvotes: 1

Algorithmist
Algorithmist

Reputation: 6695

Close your BufferedWriter Object

 FileWriter fstream = new FileWriter(outputFileName, false); //false tells to not append data.
            BufferedWriter out = new BufferedWriter(fstream);
            for (int i=0; i<numBins; ++i){
                String str=Integer.toString(hist[i]);
                str.concat("\n");
                out.write(str);
            }
            out.close();

Upvotes: 1

Related Questions