解析包含不同数据类型的字节数组,并能够使用Java正确获取每个值

时间:2013-10-23 14:55:46

标签: java arrays io

我是Java新手,从事字节数组工作。

我有一个在Database中创建的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

2 个答案:

答案 0 :(得分:0)

您可以使用longBitsToDoubleintBitsToFloat转换long(64位)或int(32位)。但是,如果浮点数具有与Java匹配的二进制布局,则必须注意;并且你已经注意以正确的顺序组装从blob读取的字节。 (使用<<运算符)。

答案 1 :(得分:0)

我认为最简单且最不容易出错的方法是使用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和右字节编码的逻辑。

相关问题