Skip () method in IO java?

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

+5
source share
2 answers

You must use a BufferedReader . Its skip method skips characters, not bytes.

To skip characters 20 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 
+7
source

Check the counter.

Complete all characters increasing the counter for each reading. When you reach the counter limit corresponding to the beginning of the skipped characters, 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 BufferedReader to improve performance, as Tunaki said (or BufferedInputStream , depending on the type of file you are reading, in a binary or text file).

+2
source

Source: https://habr.com/ru/post/1232516/


All Articles