FileInputStream skip(long) in Java

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

Syntax:

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

This method takes one argument. This method skips over and discards n bytes of data from the input stream.

The skip method may, for a variety of reasons, end up skipping over some smaller number of bytes, possibly 0.

If n is negative, the method will try to skip backwards. In case the backing file does not support backward skip at its current position, an IOException is thrown.

Note:

1. The actual number of bytes skipped is returned.

2. If it skips forwards, it returns a positive value.

3. If it skips backwards, it returns a negative value.

Parameters: One parameter is required for this method.

n: the number of bytes to be skipped.

Returns: the actual number of bytes skipped.

Throws:

IOException - if n is negative, if the stream does not support seek, or if an I/O error occurs.

Approach 1: When no exception

Java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamskip {

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

        String pathname = "D:\\hello.txt";
        File file = new File(pathname);
        FileInputStream fileInputStream =
new FileInputStream(file);

        long n = 12;

        System.out.println(fileInputStream.skip(n));
        fileInputStream.close();
    }
}

Output:

12


Approach 2: IOException

Java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamskip {

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

        String pathname = "D:\\hello.txt";
        File file = new File(pathname);
        FileInputStream fileInputStream =
new FileInputStream(file);

        long n = -12;

        System.out.println(fileInputStream.skip(n));
        fileInputStream.close();
    }
}

Output

Exception in thread "main" java.io.IOException: An attempt was made to move the file pointer before the beginning of the file at java.base/java.io.FileInputStream.skip0(Native Method) at java.base/java.io.FileInputStream.skip(FileInputStream.java:299)


No comments:

Post a Comment