markSupported() mark() reset() Java

markSupported() mark() reset() Java

Rereading from the Same Position

The same contents of a file can be again and again read by marking the position with the methods of StringBufferInputStream, inherited from its super class InputStream.

A file can be reread (reading again) from a particular location. Here, the file position is marked; execution control is taken back to the same position and reread.

markSupported() mark() reset() Java

Using these methods, helpful to read the data, the file position is marked, control is shifted back to the position and read from that position.

In the following application, the file Security.txt file is re-read again using MarkAndReset.java.

File Name: Security.txt

Security is a shared effort. Every one’s $ participation is utmost important.

File Name: MarkAndReset.java


markSupported() mark() reset() Java
Output screen onmarkSupported() mark() reset() Java

The file, Security.txt contains some data of which a few important words are re-read. The FileInputStream is chained to BufferedInputStream as this stream is the best suitable by performance-wise. Reading with BufferedInputStream is few thousand times speedier than reading with FileInputStream.

'$' symbol is chosen in the file from where the contents are read again. Every byte read by read() method is compared with '$' symbol and when '$' is encountered, the position is marked with the mark() method of BufferedInputStream. For code robustness and systematic way of code development, the BufferedInputStream is checked whether it supports the marking using markSupported() method which returns true if the stream supports.

The reset() method places the file pointer exactly at the same position where we marked with mark() method. From here, the file is read again with the usual while loop. In the program, the contents from '$' symbol are read again and again (2 times) to have grip over the marking and reading.

One thought on “markSupported() mark() reset() Java

Leave a Reply

Your email address will not be published. Required fields are marked *