Java writing to text files.

Soldato
Joined
29 Apr 2007
Posts
4,841
Location
London
Hi im writing to text files in Java using

Code:
PrintWriter out = new PrintWriter(new FileWriter("file.txt"));
int i = 0;
for (i=0; i < toPrint.length - 1; i++)
{
       out.print(toPrint [i] + "\n");
}

To print an array of 2000 words.

However it stop as soon as the file size reaches 8KB.
Have you got any ideas how I can fix this? It just stops half way through a word.
 
Last edited:
Memory issue perhaps?

I assume that your entering the \n to try and get it to put each letter on a new line?

If so, have you tried using

Code:
out.println(toPrint [i])

instead ?
 
well now im using this code

Code:
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"), int sz);
 
int i = 0;
for (i=0; i < toPrint.length - 1; i++)
{
out.write(toPrint [i])
out.newLine();
}
out.close();

That int sz bit declares the size of the buffer. What should I type in there?

Seems to work by typing 100000 in but maybe thats a silly number?
 
Last edited:
Your original code was fine, you just need to flush the PrintWriter's buffer after you exit the loop to write any data that is in the buffer.

I made 5 changes:
  1. Moved the local loop counter variable (i) into the loop, no need for it to be outside unless you have a good reason for doing so.
  2. Changed toPrint.length -1 to toPrint.length because you would chop off the last element otherwise
  3. Used println() rather than print() to write a line to the file, this eliminates the need to append "\n".
  4. Added out.flush() after the loop to empty the buffer and write any remaining data to the file.
  5. Closed the stream (a good idea unless you need to keep it open to write more data).

Code:
PrintWriter out = new PrintWriter(new FileWriter("file.txt"));
for ([COLOR="Red"]int i=0[/COLOR]; i < [COLOR="Red"]toPrint.length[/COLOR]; i++)
{
       out.[COLOR="Red"]println[/COLOR](toPrint[i]);
}
[COLOR="Red"]out.flush();[/COLOR]
[COLOR="Red"]out.close();[/COLOR]

The loop can also be replaced with an enhanced for-loop (foreach loop) if required:
Code:
for (String word : toPrint)
{
       out.println(word);
}
 
Last edited:
Thanks very much :) That works well.

Weird thing is, before reading in the original file has 2,011 words. After writing out it has 1870, im not really sure why.
 
Last edited:
Back
Top Bottom