Java - BufferedWriter newLine() method



Description

The Java BufferedWriter newLine() method is used to write a platform-independent line separator to the output stream. Instead of manually inserting line breaks (like \n or \r\n), using newLine() ensures that the correct line separator is written for the platform where the code is running.

Declaration

Following is the declaration for java.io.BufferedWriter.newLine() method.

public void newLine()

Parameters

NA

Return Value

This method does not return any value.

Exception

IOException − If an I/O error occurs.

Example - Using newLine() method

The following example shows the usage of Java BufferedWriter newLine() method.

BufferedWriterDemo.java

package com.tutorialspoint;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;

public class BufferedWriterDemo {
   public static void main(String[] args) throws IOException {
      StringWriter sw =null;
      BufferedWriter bw = null;
      String s = "Hello World!!";
            
      try {
         // create new string writer
         sw = new StringWriter();
         
         // create new buffered writer
         bw = new BufferedWriter(sw);
         
         // write string sequence to buffered writer
         bw.write(s, 0, 5);
   
         // write new line to the buffered writer
         bw.newLine();
         
         // write the next string sequence to buffered writer
         bw.write(s, 6, s.length()-6);
         
         // releases all bytes to the underlying stream
         bw.flush();

         // print
         System.out.print(sw.getBuffer());
         
      } catch(Exception e) {
         // if any I/O error occurs
         e.printStackTrace();
      } finally {
         // releases system resources from the streams
         if(sw!=null)
            sw.close();
         if(bw!=null)
            bw.close();
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Hello
World!!

Example - Writing Multiple Lines to a File

The following example shows the usage of Java BufferedWriter newLine() method.

BufferedWriterDemo.java

package com.tutorialspoint;

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

public class BufferedWriterDemo {
   public static void main(String[] args) {
      String filePath = "example.txt";

      try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
         // Write multiple lines using newLine()
         writer.write("Line 1: Hello, World!");
         writer.newLine(); // Write a line separator
         writer.write("Line 2: This is an example of newLine() method.");
         writer.newLine(); // Write another line separator
         writer.write("Line 3: Using newLine() ensures platform independence.");

         System.out.println("Lines written to the file successfully.");
      } catch (IOException e) {
         System.err.println("An error occurred: " + e.getMessage());
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Lines written to the file successfully.

File Output

Following will be the content of example.txt file

Line 1: Hello, World!
Line 2: This is an example of newLine() method.
Line 3: Using newLine() ensures platform independence.

Explanation

  • A BufferedWriter is used to write multiple lines to a file (example.txt).

  • The newLine() method is called after each write() operation to add a platform-independent line break.

  • This ensures that the lines appear correctly formatted regardless of the operating system (e.g., \n on Unix-like systems and \r\n on Windows).

  • The file will contain three lines of text, separated by line breaks.

Example - Writing Dynamic Content Line by Line

The following example shows the usage of Java BufferedWriter newLine() method.

BufferedWriterDemo.java

package com.tutorialspoint;

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

public class BufferedWriterDemo {
   public static void main(String[] args) {
      String filePath = "example.txt";

      try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
         // Simulate dynamic content
         for (int i = 1; i <= 5; i++) {
            writer.write("This is line number " + i);
            writer.newLine(); // Write a line separator after each line
         }

         System.out.println("Dynamic content written to the file successfully.");
      } catch (IOException e) {
         System.err.println("An error occurred: " + e.getMessage());
      }
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Dynamic content written to the file successfully.

File Output

Following will be the content of example.txt file

This is line number 1
This is line number 2
This is line number 3
This is line number 4
This is line number 5

Explanation

  • A loop is used to simulate dynamically generated content.

  • For each iteration, a line of text is written to the file (example.txt), followed by a platform-independent line separator using newLine().

  • This ensures that each line appears on a separate line in the output file, regardless of the system's line separator.

Key Points About newLine()

  • Platform Independence− Unlike manually adding \n or \r\n, newLine() ensures the correct line separator for the operating system.

  • Improves Readability− Makes it easier to format output in a structured and readable way.

  • Convenience− Avoids hardcoding line separators and potential cross-platform compatibility issues.

When to Use newLine()

  • When writing multiple lines of text to a file.

  • In scenarios where your application runs on different platforms and requires consistent line breaks.

  • For dynamically generating output that needs structured formatting.

These examples demonstrate practical use cases of the newLine() method, highlighting its importance for writing formatted and platform-independent text output.

Advertisements