write(char[], int, int): This method is available in the java.io.BufferedWriter class of Java.
Syntax:
void java.io.BufferedWriter.write(char[] cbuf, int off, int len) throws IOException
This method takes three arguments. This method writes a portion of an array of characters.
Ordinarily, this method stores characters from the given array into this stream's buffer, flushing the buffer to the underlying stream as needed.
Parameters: Three parameters are required for this method.
cbuf: A character array.
off: Offset from which to start reading characters.
len: Number of characters to write.
Returns: NA
Throws:
1. IndexOutOfBoundsException - If off is negative, or len is negative, or off + len is negative or greater than the length of the given array.
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 BufferedWriterwrite2 {public static void main(String[] args) throws IOException {FileWriter fileWriter = new FileWriter("D:\\hello.txt");BufferedWriter bufferedWriter =new BufferedWriter(fileWriter);char cbuf[] = { 'a', 'b', 'c', 'd', 'e' };int off = 0, len = 3;bufferedWriter.write(cbuf, off, len);System.out.println("Successfully writes");bufferedWriter.close();}}
Output:
Successfully writes
Approach 2: IndexOutOfBoundsException
Java
import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;public class BufferedWriterwrite2 {public static void main(String[] args) throws IOException {FileWriter fileWriter = new FileWriter("D:\\hello.txt");BufferedWriter bufferedWriter =new BufferedWriter(fileWriter);char cbuf[] = { 'a', 'b', 'c', 'd', 'e' };int off = 0, len = 10;bufferedWriter.write(cbuf, off, len);System.out.println("Successfully writes");bufferedWriter.close();}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.io.BufferedWriter.write(BufferedWriter.java:174)
Approach 3: IOException
Java
import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;public class BufferedWriterwrite2 {public static void main(String[] args) throws IOException {FileWriter fileWriter = new FileWriter("D:\\hello.txt");BufferedWriter bufferedWriter =new BufferedWriter(fileWriter);char cbuf[] = { 'a', 'b', 'c', 'd', 'e' };int off = 0, len = 3;bufferedWriter.close();bufferedWriter.write(cbuf, 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:171)
No comments:
Post a Comment