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?
Asked
Active
Viewed 2,669 times
5

Tunaki
- 132,869
- 46
- 340
- 423

Quan Nguyen
- 698
- 1
- 9
- 19
-
`skip` works from the current file position. For text use a reader (InputStreamReader bridges binary bytes to Unicode java text). For buffering use a Buffered~ version. – Joop Eggen Sep 29 '15 at 09:07
2 Answers
7
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

Tunaki
- 132,869
- 46
- 340
- 423
-
7@QuanNguyen - As a thumb rule, remember that *Streams work on bytes, readers / writers work on characters* – TheLostMind Sep 29 '15 at 09:03
-
Bear in mind that even `BufferedReader.skip()` may not necessarily do exactly what you want if you have characters outside the [BMP](https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane). – Phylogenesis Sep 29 '15 at 09:18
2
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).

Davide Lorenzo MARINO
- 26,420
- 4
- 39
- 56