BufferedWriter write(int) in Java

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

Syntax:

void java.io.BufferedWriter.write(int c) throws IOException

This method takes one argument. This method writes a single character.

Parameters: One parameter is required for this method.

c: int specifying a character to be written.

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 BufferedWriterwrite {
    public static void main(String[] args) throws IOException {

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

        int c = 'a';
        bufferedWriter.write(c);

        System.out.println("Successfully writes");
        bufferedWriter.close();
    }
}

Output:

Successfully writes

hello.txt => a

Approach 2: IOException 

Java

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

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

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

        int c = 'a';
        bufferedWriter.close();
        bufferedWriter.write(c);

        System.out.println("Successfully writes");

    }
}

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:132)


No comments:

Post a Comment