Home Tutorial Java Core Files Java write to file line by line

 
 

Share on Google+Share on Google+
Java write to file line by line
Posted on: January 24, 2011 at 12:00 AM
Advertisement
In this section, you will learn how to write a file line by line.

Java write to file line by line

In this section, you will learn how to write a file line by line.

It is better to use Writer class instead of OutputStream class if you want to output text to the file since the purpose of Writer classes are to handle textual content.
In the given example, we have simply create an object of BufferedWriter class and use its method write() for writing the text. With the BufferedWriter, you don't have to translate your String parameter to a byte array. The method newLine() is used for writing a new line character. We simply write two lines of text, and finally we call close() method on the BufferedWriter object before closing it.

Here is the code:

import java.io.*;

class FileWrite {
	public static void writeToFile(String text) {
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
					"C:/new.txt"), true));
			bw.write(text);
			bw.newLine();
			bw.close();
		} catch (Exception e) {
		}
	}

	public static void main(String[] args) throws Exception {
		String st1 = "Hello";
		String st2 = "Where there is will, there is a way";

		writeToFile(st1);
		writeToFile(st2);

		System.out.println("File created successfully!");
	}
}
Advertisement

Related Tags for Java write to file line by line:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 24, 2011

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com