簡體   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