LineNumberReader skip(long) in Java

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

Syntax:

long java.io.LineNumberReader.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. IOException - If an I/O error occurs.

2. IllegalArgumentException - If n is negative

Approach 1: When no exception

Java

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.StringReader;

public class LineNumberReaderskip {
    public static void main(String[] args) {

        Reader in = new StringReader("Hello");
        LineNumberReader lineNumberReader = new LineNumberReader(in);

        long n = 10;
        try {
            System.out.println(lineNumberReader.skip(n));
        } catch (IOException e) {
            System.out.println("IOException occurs");
        } catch (IllegalArgumentException e) {
            System.out.println("IllegalArgumentException occurs");
        }

    }
}

Output:

5


Approach 2: IllegalArgumentException 

Java

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.StringReader;

public class LineNumberReaderskip {
    public static void main(String[] args) {

        Reader in = new StringReader("Hello");
        LineNumberReader lineNumberReader =
new LineNumberReader(in);

        long n = -10;
        try {
            System.out.println(lineNumberReader.skip(n));
        } catch (IOException e) {
            System.out.println("IOException occurs");
        } catch (IllegalArgumentException e) {
            System.out.println("IllegalArgumentException occurs");
        }

    }
}

Output:

IllegalArgumentException occurs


Some other methods of LineNumberReader

getLineNumber()This method gets the current line number.

LineNumberReader(Reader)This method creates a new line-numbering reader, using the default input buffer size.

LineNumberReader(Reader, int)This method creates a new line-numbering reader, reading characters into a buffer of the given size.

mark(int)This method marks the present position in the stream.

read()This method read a single character.

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

readLine()This method read a line of text.

reset()This method resets the stream to the most recent mark.

setLineNumber(int)This method sets the current line number.

No comments:

Post a Comment