write(byte[], int, int): This method is available in the java.io.FileOutputStream class of Java.
Syntax:
void java.io.FileOutputStream.write(byte[] b, int off, int len) throws IOException
This method takes three arguments. This method writes len bytes from the specified byte array starting at offset off to this file output stream.
Parameters: Three parameters are required for this method.
b: the data.
off: the start offset in the data.
len: the number of bytes to write.
Throws:
1. NullPointerException - If b is null.
2. IndexOutOfBoundsException - If off is negative, len is negative, or len is greater than b.length - off.
3. IOException - if an I/O error occurs.
Approach 1: When no exception
Java
import java.io.File;import java.io.FileOutputStream;import java.io.IOException;public class FileOutputStreamwrite3 {public static void main(String[] args) throws IOException {String pathname = "D:\\hello.txt";File file = new File(pathname);FileOutputStream fileOutputStream =new FileOutputStream(file);byte b[] = { 'a', 'b', 'c', 'd', 'e', 'f' };int off = 1, len = 4;fileOutputStream.write(b, off, len);System.out.println("Successfully writes");fileOutputStream.close();}}
Output:
Successfully writes
Approach 2: NullPointerException
Java
import java.io.File;import java.io.FileOutputStream;import java.io.IOException;public class FileOutputStreamwrite3 {public static void main(String[] args) throws IOException {String pathname = "D:\\hello.txt";File file = new File(pathname);FileOutputStream fileOutputStream =new FileOutputStream(file);byte b[] = null;int off = 1, len = 4;fileOutputStream.write(b, off, len);System.out.println("Successfully writes");fileOutputStream.close();}}
Output:
Exception in thread "main" java.lang.NullPointerException at java.base/java.io.FileOutputStream.writeBytes(Native Method) at java.base/java.io.FileOutputStream.write(FileOutputStream.java:347)
Approach 3: IndexOutOfBoundsException
Java
import java.io.File;import java.io.FileOutputStream;import java.io.IOException;public class FileOutputStreamwrite3 {public static void main(String[] args) throws IOException {String pathname = "D:\\hello.txt";File file = new File(pathname);FileOutputStream fileOutputStream =new FileOutputStream(file);byte b[] = { 'a', 'b', 'c', 'd', 'e', 'f' };int off = 1, len = 10;fileOutputStream.write(b, off, len);System.out.println("Successfully writes");fileOutputStream.close();}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.io.FileOutputStream.writeBytes(Native Method) at java.base/java.io.FileOutputStream.write(FileOutputStream.java:347)
No comments:
Post a Comment