Share on Google+Share on Google+

Java Write To File By Line

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 :


class WriteToFileByLine
  public static void main(String args[])
    String pLine = "Previous Line text";
    String nLine = "New Line text";
    WriteToFileByLine wtfbl = new WriteToFileByLine();
   public void writeToFileByLine(String str)
       File file = new File("fileByLine.txt");
       FileWriter fw = new FileWriter(file, true);
       BufferedWriter bw = new BufferedWriter(fw);
      catch (Exception e)

How to Execute this example :

After doing the basic process to execute a java program write simply on command prompt as :

javac 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 :

Download Source Code


Posted on: January 17, 2012 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.

Discuss: Java Write To File By Line  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image