我正在制作有关数据压缩的项目(使用霍夫曼算法)。该项目仍在修订中。我遇到了非常有趣的问题。我需要从二进制文件中逐字节读取。我有这个文件 FileInputHelper 实现了一些方法:
import java.io.IOException;
public class FileInputHelper implements Closeable {
private FileInputStream fileInputStream;
private BufferedReader fileBufferedReader;
public FileInputHelper(File file) throws IOException {
fileInputStream = new FileInputStream(file);
fileBufferedReader = new BufferedReader(
new InputStreamReader(fileInputStream));
}
public byte readByte() throws IOException {
return (byte)fileInputStream.read();
}
public char read() throws IOException {
return (char)fileInputStream.read();
}
public String readLine() throws IOException {
return fileBufferedReader.readLine();
}
@Override
public void close() throws IOException{
fileInputStream.close();
}
}
但是当二进制文件结束时,方法应该返回-1。当然,应该如此。但是有一些测试,其中有字节等于-1,但不是最后一个。 如您所知,这非常关键。如果在中间我读到-1,我会认为文件已经结束。但事实并非如此。有什么办法可以解决这个问题吗?我可以获得 EOFException 吗?如果我的代码不好,我想听听你的建议。
最佳答案
这就是为什么InputStream.read()
在实际读取byte
时声明返回类型int
。仅int
的低字节用于数据。如果您读取 -1
字节,那么它将返回 255
并且您必须手动将其转换为 byte
。
ByteArrayInputStream in = new ByteArrayInputStream(new byte[]{1, 0, -1});
int read;
while ((read = in.read()) > -1) {
System.out.println("As int: " + read + ", as byte: " + (byte) read);
}
将输出:
As int: 1, as byte: 1
As int: 0, as byte: 0
As int: 255, as byte: -1
您可能不想在 public char read()
方法中使用 char
,因为 char
是无符号的并且无法保存-1
。返回 int
并遵循通常的约定更具可读性。
关于java - 如何从 FileInputStream 获取 EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54349133/