java, outputting array to file - not working as expected

GeX

GeX

Soldato
Joined
17 Dec 2002
Posts
6,981
Location
Manchester
Hi. Wonder if anyone can help me here.

Basically what i'm working on is a bit of code that reads an array from a file, sorts it, and then writes it back. It's not part of any bigger project, i'm just trying to understand how it all works :)

Reading from the file works fine, sorting the array works fine, but writing back to the file does not. It only outputs one element of the array, despite outputting the sorted array to the screen correctly. It is probably a silly mistake that i've made and can't spot it for looking.

Code:
	for (int i = 0; i < test.length; i++)
	     {




	       String[] tempRow = test[i];
	       for (int j = 0; j < tempRow.length; j++)
	       {

	        System.out.print(tempRow[j] + " | "); //debug screen output

	    try {

	    BufferedWriter out = new BufferedWriter(new FileWriter("c://java//output.txt"));
		out.write(tempRow[j] + " | ");
        out.close();
            } catch (IOException e) { }

	       }
	       System.out.println(); // debug screen output
		}

What I don't get is, despite the code handling.. actually.. i think i just understood... It is re-writing the file everytime isn't it. Balls. There is only one element appearing because that is the last one to be written.. hmmm... help?
 
hmm blonde moment, nevermind - sorted now. amazing what a cup of coffee does :D
 
EDIT: Now I've read the thread, ignore.

Why are you creating your buffered writer inside your loop?

You realise you can create it once, call write multiple times (within the loop) then close it afterwards?
 
Last edited:
Note aswell that you should probably move the out.close() into a finally statement, so that it is executed regardless to whether it throws an exception or not. Unexpected crap can happen when you don't close resources manually. Like so:

Code:
BufferedWriter out = null;
try {
    out = new BufferedWriter(new FileWriter("file.txt");
    
    // out.write all elements
} catch (IOException ex) {
   // do crap
} finally {
    if (out != null) out.close();
}
 
\r\n is a carriage return line feed, try that.

Not very platform independent though, is it?

The OP should use println in the PrintWriter class (created with an OutStream derived from his file) to output lines with a newline at the end.
 
Back
Top Bottom