FilterWriter write(String, int, int) in Java

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

Syntax:

void java.io.FilterWriter.write(String str, 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.

str: String to be written.

off: Offset from which to start reading characters.

len: Number of characters to be written.

Returns: NA

Throws:

1. IndexOutOfBoundsException - If the values of the off and len parameters cause the corresponding method of the underlying Writer to throw an IndexOutOfBoundsException.

2. IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.FilterWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

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

        Writer writer = new StringWriter();
        FilterWriter filterWriter = new FilterWriter(writer) {
        };

        String str = "Hello Java";
        int off = 0, len = 4;
        try {
            filterWriter.write(str, off, len);
            System.out.println("Successfully writes into the filter writer");
        } catch (IndexOutOfBoundsException e) {
            System.out.println("IndexOutOfBoundsException occurs");
        } catch (IOException e) {
            System.out.println("IOException occurs");
        }
        filterWriter.close();
    }
}

Output:

Successfully writes into the filter writer


Approach 2: IndexOutOfBoundsException 

Java

import java.io.FilterWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

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

        Writer writer = new StringWriter();
        FilterWriter filterWriter = new FilterWriter(writer) {
        };

        String str = "Hello Java";
        int off = 0, len = 14;
        try {
            filterWriter.write(str, off, len);
            System.out.println("Successfully writes into the filter writer");
        } catch (IndexOutOfBoundsException e) {
            System.out.println("IndexOutOfBoundsException occurs");
        } catch (IOException e) {
            System.out.println("IOException occurs");
        }
        filterWriter.close();
    }
}

Output:

IndexOutOfBoundsException occurs


Some other methods of FilterWriter.

close()This method closes the stream, flushing it first. 

flush()This method flushes the stream.

write(int)This method writes a single character.

write(char[], int, int)This method writes a portion of an array of characters.

No comments:

Post a Comment