鉴于我有一个文本文件,我知道我可以使用FileReader
阅读chars
:从文本文件如何指定字符在Java中读取
in = new FileReader("myFile.txt");
int c;
while ((c = in.read()) != -1)
{ ... }
不过,我in.read()
后,将有可能通过一个字符回溯?有什么方法可以改变in.read()
指向哪里?也许我可以使用迭代器?
鉴于我有一个文本文件,我知道我可以使用FileReader
阅读chars
:从文本文件如何指定字符在Java中读取
in = new FileReader("myFile.txt");
int c;
while ((c = in.read()) != -1)
{ ... }
不过,我in.read()
后,将有可能通过一个字符回溯?有什么方法可以改变in.read()
指向哪里?也许我可以使用迭代器?
如果您只需要回溯一个字符,请考虑将前一个字符保留在变量中,然后在需要时引用该字符。
如果您需要回溯未指定的金额,大多数文件可能更容易将文件内容保存在内存中并在其中处理内容。
正确答案取决于上下文。
我们可以使用java.io.PushbackReader.unread
https://docs.oracle.com/javase/7/docs/api/java/io/PushbackReader.html
请参考这里的样本:http://tutorials.jenkov.com/java-io/pushbackreader.html
假设你正在谈论的输入流。 您可以使用int java.io.InputStream.read(byte [] b,int off,int len)方法代替,第二个参数“off”(用于偏移量)可以用作inputStream的起点你想读。
一种替代方法是使用in.reset()第一重新定位读者的流的开始,然后in.skip(长N)移动到期望的位置
取决于你想达到什么,你可以看看PushbackInputStream或RandomAccessFile。
查找以下两个片段来演示不同的行为。对于文件abc.txt
都包含一行foobar12345
。
PushbackInputStream允许您更改流中的数据以供稍后阅读。
try (PushbackInputStream is = new PushbackInputStream(
new FileInputStream("abc.txt"))) {
// for demonstration we read only six values from the file
for (int i = 0; i < 6; i++) {
// read the next byte value from the stream
int c = is.read();
// this is only for visualising the behavior
System.out.print((char) c);
// if the current read value equals to character 'b'
// we push back into the stream a 'B', which
// would be read in the next iteration
if (c == 'b') {
is.unread((byte) 'B');
}
}
}
outout
foobBa
的RandomAccessFile中,您可以阅读特定的数据流中的偏移值。
try (RandomAccessFile ra = new RandomAccessFile("abc.txt", "r")) {
// for demonstration we read only six values from the file
for (int i = 0; i < 6; i++) {
// read the next byte value from the stream
int c = ra.read();
// this is only for visualising the behavior
System.out.print((char) c);
// if the current read value equals to character 'b'
// we move the file-pointer to offset 6, from which
// the next character would be read
if (c == 'b') {
ra.seek(6);
}
}
}
输出
foob12
PushbackReader。不是PushbackInputStream。 – saka1029