如何在java中读取文本文件中指定的字符

如何在java中读取文本文件中指定的字符,java,file-io,Java,File Io,如果我有一个文本文件,我知道我可以使用FileReader读取chars: in = new FileReader("myFile.txt"); int c; while ((c = in.read()) != -1) { ... } 但是,在.read()中执行之后,是否可以回溯一个字符?是否有任何方法可以更改.read()中的指向的位置?也许我可以使用一个迭代器?< /p> 如果只需要回溯一个字符,考虑将前一个字符保持在一个变量中,然后在需要时引用它。 如果您需要回溯未指定的数量,那么对于

如果我有一个文本文件,我知道我可以使用
FileReader
读取
chars

in = new FileReader("myFile.txt");
int c;
while ((c = in.read()) != -1)
{ ... }

但是,在.read()中执行
之后,是否可以回溯一个字符?是否有任何方法可以更改.read()
中的
指向的位置?也许我可以使用一个迭代器?< /p> 如果只需要回溯一个字符,考虑将前一个字符保持在一个变量中,然后在需要时引用它。
如果您需要回溯未指定的数量,那么对于大多数文件来说,将文件内容保存在内存中并在内存中处理内容可能更容易


正确答案取决于上下文。

我们可以使用java.io.PushbackReader.unread


请参考此处的示例:

假设您谈论的是输入流。 您可以使用intjava.io.InputStream.read(字节[]b,int off,int len)方法,第二个参数“off”(用于偏移量)可以用作要读取的InputStream的起点


另一种方法是先使用in.reset()将读卡器重新定位到流的开头,然后使用in.skip(long n)移动到所需的位置,具体取决于您想要实现的目标,您可以查看或查看

找到下面两个片段来演示不同的行为。对于这两个文件,
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');
        }
    }
}
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);
        }
    }
}

推送阅读器。不是PushbackInputStream。
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