例子
以下示例显示java.io.LineNumberReader.mark(int readAheadLimit)方法的用法。
package com.jc2182;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class LineNumberReaderDemo {
public static void main(String[] args) throws IOException {
FileReader fr = null;
LineNumberReader lnr = null;
int i;
try {
// create new reader
fr = new FileReader("C:/test.txt");
lnr = new LineNumberReader(fr);
// reads and prints data from reader
System.out.println((char)lnr.read());
System.out.println((char)lnr.read());
// mark invoked at this position
lnr.mark(0);
System.out.println("mark() invoked");
System.out.println((char)lnr.read());
System.out.println((char)lnr.read());
// if this reader supports mark() an reset()
if(lnr.markSupported()) {
// reset() repositioned the reader to the mark
lnr.reset();
System.out.println("reset() invoked");
System.out.println((char)lnr.read());
System.out.println((char)lnr.read());
}
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
} finally {
// closes the stream and releases system resources
if(fr!=null)
fr.close();
if(lnr!=null)
lnr.close();
}
}
}
假设我们有一个文本文件c:/test.txt ,其内容如下。该文件将用作示例程序的输入-
让我们编译并运行以上程序,这将产生以下结果-
A
B
mark() invoked
C
D
reset() invoked
C
D