Write Text To File In New Line.

In this tutorial you will learn how to write text into file in a new line.

Write Text To File In New Line.

In this tutorial you will learn how to write text into file in a new line.

Write Text To File In New Line

Write Text To File In New Line.

In this tutorial you will learn how to write text into file in a new line.

When you are writing in a file you may be required to finish the line and want to write the other text in a new line. For this BufferedWriter class provides a method newLine(). This method can be used wherever you want to finish the previous line and want to write new text in new line.

Here I am giving a simple example which will demonstrate you how to use the newLine() method. In the example given below I have first created a new text file named "newLineFileWriter.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 :

WriteToFileNewLine.java

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

class WriteToFileNewLine
    {
       public static void main(String args[]) throws IOException 
         {
             BufferedWriter bw = null;
	try
	{
	    File file = new File("newLineFileWriter.txt");
  	    FileWriter fw = new FileWriter(file);
	    bw = new BufferedWriter(fw);
  	    bw.write("These text are written in first line.");
	    bw.newLine();
            bw.write("These text are written in a new line.");
        }
	 catch (Exception e) 
	    {
	            System.out.println(e);
	    } 
	finally
	 {
           try
	    {
	     if (bw != null)
	      {
               	bw.flush();
	       	bw.close();
              }
	    }
	  catch (IOException ex) 
	    {
	     ex.printStackTrace();
            }
	}
	System.out.println("\n ----------**-----Text is written into file successfully-----**------------");         
    }
}    

How to Execute this example :

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

javac WriteToFileNewLine.java to compile the program

And after successfully compilation to run simply type as :

java WriteToFileNewLine

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 programmatically. like as :

Download Source Code