我想读取文本文件,然后获取读取文件的偏移量。我尝试了以下程序,但事情是我不想使用RandomAccessFile,我该怎么做。
RandomAccessFile access = null;
try {
access = new RandomAccessFile(file, "r");
if (file.length() < addFileLen) {
access.seek(file.length());
} else {
access.seek(addFileLen);
}
} catch (Exception e) {
e.printStackTrace();
}
String line = null;
try {
while ((line = access.readLine()) != null) {
System.out.println(line);
addFileLen = file.length();
}
答案 0 :(得分:1)
如果要连续阅读文件,可以执行以下操作。这通过实际上不读取文件的末尾。您遇到的问题是,最后可能没有完整的行甚至是完整的多字节字符。
class FileUpdater {
private static final long MAX_SIZE = 64 * 1024;
private static final byte[] NO_BYTES = {};
private final FileInputStream in;
private long readSoFar = 0;
public FileUpdater(File file) throws FileNotFoundException {
this.in = new FileInputStream(file);
}
public byte[] read() throws IOException {
long size = in.getChannel().size();
long toRead = size - readSoFar;
if (toRead > MAX_SIZE)
toRead = MAX_SIZE;
if (toRead == 0)
return NO_BYTES;
byte[] bytes = new byte[(int) toRead];
in.read(bytes);
readSoFar += toRead;
return bytes;
}
}