Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip() method in IO java?

I know that skip(long) method of FileInputStream skips bytes from the starting position of the file and places the file pointer. But If we want to skip only 20 characters in the middle of the file, and the remaining part of the file as to be read, what we should do?

like image 864
Quan Nguyen Avatar asked Sep 29 '15 08:09

Quan Nguyen


2 Answers

You should use a BufferedReader. Its skip method skips characters and not bytes.

To skip 20 characters from an existing FileInputStream:

BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
// read what you want here
reader.skip(20);
// read the rest of the file after skipping
like image 124
Tunaki Avatar answered Oct 25 '22 23:10

Tunaki


Mantain a counter.

Loop all characters increasing the counter for each read. When you reach the counter limit corresponding to the start of characters to be skipped, skip the characters you need to skip.

int counter = 0;
while (counter < START_SKIP) {
    int x = input.read();
    // Do something
}
input.skip(NUM_CHARS_TO_SKIP);
...
// Continue reading the remainings chars

If necessary use a BufferedReader to improve performances as Tunaki said (or BufferedInputStream depending on type of file you are reading, if binary or text file).

like image 20
Davide Lorenzo MARINO Avatar answered Oct 25 '22 23:10

Davide Lorenzo MARINO