In this tutorial you will learn how to write to file by line
Java Write To File By Line
In this tutorial you will learn how to write to file by line
Write to a file by line using java you can use the newLine() method of BufferedWriter class. newLine() method breaks the continuous line into a new line.
Here I am going to give the simple example which will demonstrate you how to write to file by line. In this example I have first created a new text file named "fileByLine.txt" using the File class. This (File) class represents a file and directory path name abstractly. Then created a FileWriter constructor and wrapped the file object to it to write a stream of characters. Finally I have used the BufferedWriter class to write into a character-output stream. This (BufferedWriter) class provides the newLine() method to write text in a new line.
Example :
WriteToFileByLine.java
import java.io.*; class WriteToFileByLine { public static void main(String args[]) { String pLine = "Previous Line text"; String nLine = "New Line text"; WriteToFileByLine wtfbl = new WriteToFileByLine(); wtfbl.writeToFileByLine(pLine); wtfbl.writeToFileByLine(nLine); } public void writeToFileByLine(String str) { try { File file = new File("fileByLine.txt"); FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw); bw.write(str); bw.newLine(); bw.close(); } catch (Exception e) { System.out.println(e); } } }
How to Execute this example :
After doing the basic process to execute a java program write simply on command prompt as :
javac WriteToFileByLine.java to compile the program
And after successfully compilation to run simply type as :
java WriteToFileByLine
Output :
When you will execute this example a text file will be created on the specified place as the path given by you with containing the text that you are trying to write in that file by java program like as :