主营:Java的RandomAccessFile的EOFException类
package main;
import racreader.RAFReader;
public class RandomAccessFile {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Wrong arguments length");
System.exit(1);
}
try {
RAFReader reader = new RAFReader (args[0]);
try {
String output = reader.readUTF(Integer.parseInt(args[1]));
System.out.print(output);
} catch (Exception e) {
System.err.println(e.toString());
} finally {
reader.close();
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
RAFReader:
package racreader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RAFReader {
private final String fileName;
private final RandomAccessFile reader;
public RAFReader(String fileName) throws FileNotFoundException {
this.fileName = fileName;
this.reader = openFile();
}
private RandomAccessFile openFile() throws FileNotFoundException {
RandomAccessFile reader = new RandomAccessFile(fileName, "r");
return reader;
}
public String readUTF(int offset) throws IOException {
reader.seek(offset);
String output = reader.readUTF();
return output;
}
public void close() throws IOException {
reader.close();
}
}
的问题是在EOFException类中的每个文件(即使是在UTF8编码),每所抵消。为什么?
UPD:我试图让我的程序与文件正在与此内容:
Это тест UTF-8 чтения
它只有offset = 0
工作正常。任何其他的偏移量都会引发EOFException。
但是有时我在阅读开始时会用一些'RandomAccessFile'偏移量来获得一些特殊的符号。如何自动同步UTF'InputStream'? – michaeluskov
如果偏移量是要跳过的字符数,请确保您正在使用'Reader#skip()',而不是'RandomAccessFile#seek()'。后者将以字节为单位,因此它可以将流指向由几个字节编码的字符的中间,因此是特殊符号。 –