掃描儀不適用於這種用例。掃描儀將讀取的數據超出其目前使用的 - 如果你跟蹤寫入字節,比你會得到預期的其他結果:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class S {
private final static class ProgressStream extends FileInputStream {
private int bytesRead;
private ProgressStream(File file) throws FileNotFoundException {
super(file);
}
@Override
public int read() throws IOException {
int b = super.read();
if (b != -1)
bytesRead++;
return b;
}
@Override
public int read(byte[] b) throws IOException {
int read = super.read(b);
if (read != -1)
bytesRead += read;
return read;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int read = super.read(b, off, len);
if (read != -1)
bytesRead += read;
return read;
}
}
public S() throws Exception {
ProgressStream progressStream = new ProgressStream(new File("file.txt"));
Scanner sc = new Scanner(progressStream);
while (sc.hasNext()) {
sc.nextInt();
System.out.println("Read = " + progressStream.bytesRead + " bytes");
}
System.out.println("done");
}
public static void main(String arg[]) throws Exception {
new S();
}
}
輸入,文件
123 456 789
它輸出
Read = 13 bytes
Read = 13 bytes
Read = 13 bytes
done
所以你將不得不通過自己的實現類似掃描儀的功能...
import java.io.File;
import java.io.FileInputStream;
public class S {
public S() throws Exception {
FileInputStream stream = new FileInputStream(new File("file.txt"));
int b;
StringBuilder lastDigits = new StringBuilder();
int read = 0;
while ((b = stream.read()) != -1) {
read++;
char c = (char) b;
if (Character.isDigit(c)) {
lastDigits.append(c);
} else if (lastDigits.length() > 0) {
System.out.println("found int "+Integer.parseInt(lastDigits.toString()));
System.out.println("Read = "+read+" bytes");
lastDigits = new StringBuilder();
}
}
if (lastDigits.length() > 0) {
System.out.println("found int "+Integer.parseInt(lastDigits.toString()));
System.out.println("Read = "+read+" bytes");
}
System.out.println("done");
}
public static void main(String arg[]) throws Exception {
new S();
}
}
將輸出
found int 123
Read = 4 bytes
found int 456
Read = 8 bytes
found int 789
Read = 13 bytes
done
'nextInt()'將讀取的數,這可能是個字節的可變數量,這取決於數多長時間是在字符的字符串表示。 – rgettman
你可以發佈一個file.txt的例子嗎? – slartidan
要獲取讀取字節數,您可以鉤住/裝飾文件的InputStream。 – qqilihq