The mark() method mark a position in the input to which the stream can be reset by calling the reset() method
OR
The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream.
In short : mark() and reset() allows us to go backward i.e. to the stream that has already been read.
We will read c:/myFile.txt and c:/myFile.txt looks like this >
Line 1
Line 2
Line 3
Line 4
|
Program to use Mark and Reset methods of BufferedReader >
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class BufferedReaderMarkAndResetMethods {
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader("c:/myFile.txt");
br = new BufferedReader(fr);
//check whether InputStream supports mark/reset or not
if(!br.markSupported()){
System.out.println("mark/reset not supported");
System.exit(0);
}
System.out.println(br.readLine()); // Print -> Line 1
// mark -> Line 2
br.mark(0);
System.out.println(br.readLine()); // Print -> Line 2
System.out.println(br.readLine()); // Print -> Line 3
System.out.println("call reset() first time");
// reset to marked point i.e. to Line 2
br.reset();
System.out.println(br.readLine()); // Print -> Line 2
// mark -> Line 3
br.mark(0);
System.out.println(br.readLine()); // Print -> Line 3
System.out.println(br.readLine()); // Print -> Line 4
System.out.println("call reset() second time");
// reset to marked point i.e. to Line 3
br.reset();
System.out.println(br.readLine()); // Print -> Line 3
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*OUTPUT
Line 1
Line 2
Line 3
call reset() first time
Line 2
Line 3
Line 4
call reset() second time
Line 3
*/
|
Note : before making call to reset() method, stream must have been marked using mark() method.
RELATED LINKS>
Program to How to use Mark and Reset methods with BufferedInputStream
Difference between FileReader and BufferedReader in java file IO
Program to Encrypt and decrypt text using password - Write encrypted text to file | Read encrypted text from file in java
Labels:
Core Java
File IO/File handling