BufferedWriter newLine() in Java

newLine(): This method is available in the java.io.BufferedWriter class of Java.

Syntax:

void java.io.BufferedWriter.newLine() throws IOException

This method writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.

Parameters: NA

Returns: NA

Throws:

IOException - If an I/O error occurs

Approach 1: When no exception

Java

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

public class BufferedWriternewLine {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        bufferedWriter.newLine();
        System.out.println("Successfully writes a line separator");
        bufferedWriter.close();
    }
}

Output:

Successfully writes a line separator


Approach 2: IOException 

Java

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

public class BufferedWriternewLine {
    public static void main(String[] args) throws IOException {

        FileWriter fileWriter = new FileWriter("D:\\hello.txt");
        BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

        bufferedWriter.close();
        bufferedWriter.newLine();
        System.out.println("Successfully writes a line separator");

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedWriter.ensureOpen(BufferedWriter.java:107) at java.base/java.io.BufferedWriter.write(BufferedWriter.java:224) at java.base/java.io.Writer.write(Writer.java:249) at java.base/java.io.BufferedWriter.newLine(BufferedWriter.java:246)


No comments:

Post a Comment