Signup/Sign In

Java BufferedWriter newLine() Method

In this tutorial, we will learn about newLine() method of BufferedWriter class in Java. This method is used to write the new line on the BufferedWriter. With this function, BufferedWriter will start writing from the next line. The newLine() adds a line separator, The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.

Syntax

Here is the syntax of this method. This method does not accepts any parameter neither return any value.

public void newLine() throws IOException

Example of BufferedWriter without using newLine():

In this example, we can see the output is in a single line only the reason behind this is we directly written two characters on the BufferedWriter without using newLine() so it is written in a single line.

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		StringWriter stringWriter = new StringWriter(); 
		BufferedWriter buffWriter = new BufferedWriter(stringWriter);
		buffWriter.write(65); 
		buffWriter.write(66); 
		buffWriter.flush(); 
		System.out.println( stringWriter.getBuffer()); 
	} 
}


AB

Example of BufferedWriter newLine():

This program is the same as the program give above the only difference is we used newLine() method after writing the first character and this is why the characters in the output are in multiple lines. We called newLine() method twice and that's why it added two blank lines in the output.

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
		StringWriter stringWriter = new StringWriter(); 
		BufferedWriter buffWriter = new BufferedWriter(stringWriter);
		buffWriter.write(65); 
		buffWriter.newLine();
		buffWriter.newLine();
		buffWriter.write(66); 
		buffWriter.flush(); 
		System.out.println( stringWriter.getBuffer()); 
	} 
}


A

B

enlightenedThe newLine() method of BufferedWriter class in Java is used to separate the next line as a new line. It is used as a write separator in buffered writer stream.

mailConclusion:

In this tutorial, we learned about newLine() method of BufferedWriter class in Java. The newLine() adds is a line separator, The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.