Java write to 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.

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!");
	}
}

Ads