鑑於我有一個文本文件,我知道我可以使用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