[英]Parsing byte array that contains different data types and able to get each value correctly using Java
我是Java新手,致力于字节数组。
我有一个在数据库中创建的Blob,其中包含double和float值。 现在,我必须将其读入字节数组,并且应该能够分别获取float和double。
我将blob信息读入字节数组,如下所示:
FileInputStream fin = new FileInputStream(file);
byte[] fileContent = new byte[(int)file.length()];
fin.read(fileContent);
并像读取字节数组
for(int i = 0; i < fileContent.length; i++)
{
System.out.println("bit " + i + "= " + fileContent[i]);
}
这是给字节
bit 0= -57
bit 1= -16
bit 2= -90
bit 3= -109
bit 4= 66
bit 5= -90
bit 6= 116
bit 7= -25
bit 8= -100
您可以使用longBitsToDouble和intBitsToFloat转换long
(64位)或int
(32位)。 但是,必须注意浮点数的二进制布局是否与Java匹配; 并且您要注意以正确的顺序汇编从blob读取的字节。 (使用<<
运算符)。
我认为最简单,最不容易出错的方法是使用ByteBuffer。 这是一个包含两个测试用例的示例,第一个创建一个二进制文件,第二个读取它。 请注意,您可以将字节编码设置为little endian或big endian。
import org.junit.Test;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class ByteStreamWriteRead {
@Test
public void write() throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(32);
buffer.order(ByteOrder.BIG_ENDIAN);
System.out.println("Putting: " + Math.PI + ", " + (float) Math.PI);
buffer.putDouble(Math.PI);
buffer.putFloat((float) Math.PI);
File file = new File("C:/tmp/file.bin");
file.createNewFile();
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(buffer.array(), 0, buffer.position());
}
}
@Test
public void read() throws IOException {
File file = new File("C:/tmp/file.bin");
byte[] a = new byte[32];
if (file.exists()) {
try (FileInputStream fis = new FileInputStream(file)) {
fis.read(a);
}
ByteBuffer buffer = ByteBuffer.wrap(a);
buffer.order(ByteOrder.BIG_ENDIAN);
System.out.println(buffer.getDouble());
System.out.println(buffer.getFloat());
} else {
System.out.println("File doesn't exist");
}
}
}
请注意:上面的示例并未显示读取或写入文件的最有效方法。 您应该使用缓冲的读取器/写入器,并重用ByteBuffer一次读取一个字节块。 那是特定于应用程序的。 上面的示例仅显示了使用ByteBuffer和右字节编码的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.