BufferedReader skip(long) in Java

skip(long): This method is available in the java.io.BufferedReader class of Java.

Syntax:

long java.io.BufferedReader.skip(long n) throws IOException

This method takes one argument. This method skips characters.

Parameters: One parameter is required for this method.

n: The number of characters to skip.

Returns: The number of characters actually skipped.

Throws:

1. IllegalArgumentException - If n is negative.

2. IOException - If an I/O error occurs

Approach 1: When no exception

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

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

        FileReader fileReader = new FileReader("D:\\hello.txt");
        BufferedReader bufferedReader =
new BufferedReader(fileReader);

        long n = 2;

        System.out.println(bufferedReader.skip(n));

        bufferedReader.close();

    }
}

Output:

2


Approach 2: IllegalArgumentException 

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

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

        FileReader fileReader = new FileReader("D:\\hello.txt");
        BufferedReader bufferedReader =
new BufferedReader(fileReader);

        long n = -2;

        System.out.println(bufferedReader.skip(n));

        bufferedReader.close();

    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: skip value is negative at java.base/java.io.BufferedReader.skip(BufferedReader.java:407)



Approach 3: IOException 

Java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

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

        FileReader fileReader = new FileReader("D:\\hello.txt");
        BufferedReader bufferedReader =
new BufferedReader(fileReader);

        long n = 2;
        bufferedReader.close();
        System.out.println(bufferedReader.skip(n));

    }
}

Output:

Exception in thread "main" java.io.IOException: Stream closed at java.base/java.io.BufferedReader.ensureOpen(BufferedReader.java:122) at java.base/java.io.BufferedReader.skip(BufferedReader.java:410)


No comments:

Post a Comment