繁体   English   中英

如何在Java中读取来自文本文件的指定字符

[英]How can specified chars from a text file be read in java

给定我有一个文本文件,我知道我可以使用FileReader来读取chars

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(long n)移至所需位置

根据您要实现的目标,您可以查看PushbackInputStreamRandomAccessFile

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

外出

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM