我正在尝试从bin文件中读取数字,当它得到的数字大于256时,它将对该数字执行modulu(256),例如: 我要读取的数字是258,从文件读取的数字是(2)=> 258mod256 = 2 如何读取完整号码? 这是代码段:
InputStream ReadBinary = new BufferedInputStream(new FileInputStream("Compressed.bin"));
int BinaryWord = 0;
while(BinaryWord != -1) {
BinaryWord = ReadBinary.read();
if(BinaryWord != -1)
System.out.println(BinaryWord + ": " + Integer.toBinaryString(BinaryWord));
用于写入文件的代码:
DataOutputStream binFile = new DataOutputStream(new FileOutputStream("C:\\Users\\George Hanna\\eclipse-workspace\\LZW\\Compressed.bin"));
//convert codewords to binary to send them.
for(int i=0;i<result.size();i++)
try {
IOFile.print(Integer.toBinaryString(result.get(i))+ " ");
binFile.writeByte(result.get(i));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
binFile.close();
答案 0 :(得分:0)
仅提供一些有关整数存储方式的背景:
总结起来,您的文件由 bytes 组成。每个字节的值都在0到255之间。
要表示32位int,您需要4个字节。
Java具有int(4个字节)和long(8个字节)。
将数据存储在二进制文件中的最简单方法是使用DataOutputStream
,然后使用DataInputStream
进行读取。它将为您处理所有这些转换。
DataOutputStream out = new DataOutputStream(new FileOutputStream("intFile.bin"));
out.writeInt(123456789);
out.close();
DataInputStream in = new DataInputStream(new FileInputStream("intFile.bin"));
System.out.println(in.readInt());
in.close();
要从文件中获取单个字节,请执行以下操作:
InputStream in_bytes = new FileInputStream("intFile.bin");
int nextByte = in_bytes.read();
while(nextByte != -1) {
System.out.println(nextByte);
nextByte = in_bytes.read();
}
in_bytes.close();
要将单个字节写入文件,请执行以下操作:
OutputStream out_bytes = new FileOutputStream("intFile.bin");
out_bytes.write(1);
out_bytes.write(2);
out_bytes.write(3);
out_bytes.write(4);
out_bytes.close();
但是正如您已经意识到的那样,您在这里写的是字节,因此限制在0到255之间。