954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Writing to same file repeatedly

I'm trying to write some code that will write certain variables to a text file and create a simple record system. So when a button is clicked the variables are calculated and written to a text file. How can I set it up so that when the button is clicked again and the variables change due to the new values, the new set of variables are written on a different line in the text file and don't simple overwrite the old ones. So there would be one record per line.

This is the code I have for the writer component of the programme so far:

try
			{
				FileWriter writer = new FileWriter("YachtClubRecords.txt");
				writer.write(outputName);
				writer.write(outputLength);
				writer.write(durationType);
				writer.write(outputCost);
				writer.flush();
				writer.close();
			}

			catch(IOException ioe)
			{
				System.out.println("IO Exception");
			}


At the moment it obviously overwrites the previous record again and again. Thanks.

exi
Newbie Poster
3 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 
Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

Thanks that fixed the original problem. My current code is as follows:

try
			{
				FileWriter writer = new FileWriter("YachtClubRecords.txt", true);
				writer.write("\n" + outputName);
				writer.write(", " + outputLength);
				writer.write(", " + durationType);
				writer.write(", " + outputCost);
				writer.flush();
				writer.close();
			}

			catch(IOException ioe)
			{
				System.out.println("IO Exception");
			}


This is meant to print every record to a separate line. But when I check the text file in notepad all the records are on the same line. Although when I copy and paste it here, they're on separate lines...

And help would be appreciated. Thanks.

exi
Newbie Poster
3 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

That's just notepad showing its age. Use wordpad. Or a decent editor.

JamesCherrill
Posting Genius
Moderator
6,370 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

I found the problem. Windows doesn't like \n for some reason. \r\n works well.

Thanks for the help guys

exi
Newbie Poster
3 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: