Share on Google+Share on Google+

Java write to file line by line

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:


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

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


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


Posted on: January 24, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.