BufferedWriter write(String, int, int) in Java

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

Syntax:

void java.io.BufferedWriter.write(String s, int off, int len) throws IOException

This method takes three arguments. This method writes a portion of a String.

Parameters: Three parameters are required for this method.

s: String to be written.

off: Offset from which to start reading characters.

len: Number of characters to be written.

Throws:

1. IndexOutOfBoundsException - If off is negative, or off + len is greater than the length of the given string.

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

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

        String s = "hello java program";
        int off = 0, len = 10;
        bufferedWriter.write(s, off, len);

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

Output:

Successfully writes

hello.txt = > hello java

Approach 2: IndexOutOfBoundsException 

Java

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

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

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

        String s = "hello java program";
        int off = -1, len = 10;
        bufferedWriter.write(s, off, len);

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

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin -1, end 9, length 18 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3734) at java.base/java.lang.String.getChars(String.java:873) at java.base/java.io.BufferedWriter.write(BufferedWriter.java:229)



Approach 3: IOException

Java

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

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

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

        String s = "hello java program";
        int off = 0, len = 10;
        bufferedWriter.close();
        bufferedWriter.write(s, off, len);

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


No comments:

Post a Comment