my dog learned polymorphism
The moose likes Beginning Java and the fly likes File writing 1 line at a time Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "File writing 1 line at a time" Watch "File writing 1 line at a time" New topic

File writing 1 line at a time

Barry Brashear
Ranch Hand

Joined: Jun 05, 2001
Posts: 303
How can I set up an output file and and write so each write goes on a
separate line?

Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
You can create an external text file with

FileWriter writer = new FileWriter(fileName);

where fileName is the name of the file you want to create.

Be careful. With this constructor of FileWriter, if the file already exists, it will be overwritten.

Then you can wrap it in a PrintWriter.

PrintWriter output = new PrintWriter(writer);

and then to write a line to the file and include a newline in the output, you would use


Make sure that you close the PrintWriter so that any text buffered in memory is written to the file.

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

This code is for JDK 1.5:

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: File writing 1 line at a time
It's not a secret anymore!