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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 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.
@km1 How is that relevant? Ivan is not telling him to close it specifically in that method.
@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 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.