0

I am trying to write a two dimensional array to a file using this simple code:

public void writeZ(PrintWriter out) { 
    for(int i=0;i<z.length;i++) {
    int count = 0;
    for (int j=0; j<z[i].length; j++) {
         out.print(z[i][j] + " ");
         count++;
    }
    System.out.print( count);
    out.println();
    }
}

Note: The count is just for debugging

My problem is that the file size doesn't match the array size.
The number of lines is correct (45) but the last line as 1643 numbers instead 6006 as in the array.

Any ideas what is the problem?

Alex K
  • 22,315
  • 19
  • 108
  • 236
Tal Baumel
  • 31
  • 6

1 Answers1

5

You probably don't close the writer and don't call flush. Try doing this in the end:

out.flush();
out.close();

Also please see this for more information on the subject.

Community
  • 1
  • 1
Ivan Koblik
  • 4,285
  • 1
  • 30
  • 33
  • 1
    Close the writer from where it is opened. I personally don't like methods to close my Writers. Rule of thumb is if you didn't open it then you probably shouldn't close it. – km1 Sep 19 '12 at 14:29
  • @km1 Absolutely agree, I haven't given a complete solution just an idea of what might be wrong. Also, it should be enough to just close the stream, as closing triggers flush. – Ivan Koblik Sep 19 '12 at 14:31
  • @km1 How is that relevant? Ivan is not telling him to close it specifically in that method. – jn1kk Sep 19 '12 at 14:32
  • 1
    @jsn, just letting the OP know not to close it. He didn't specifically say in the method nor did he specify not in the method. – km1 Sep 19 '12 at 14:39
  • @km1 Then you are just assuming what he meant. For the love of God Ivan, please clarify to close it at the end of the program. XD – jn1kk Sep 19 '12 at 14:53