开发者

Read a binary file in Java

I have a java program that stores a byte array of 128 bytes length in a MySQL "BINARY (128)" field.

Then, with PHP I access to the database and I give the option to export this data into a file, so I unpack() the binary data, and write it into a fil开发者_高级运维e.

This file then, has to be read in a Java program that I am writing, but I can't find how I have to read this data. Any suggestion?

I tried with:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = 0;
while (i < 128) {
  System.out.println(baos.read());
  i++;
}

But bis.read() returns an int, and the byte array I sent to the mysql db was a string: "text".getBytes("utf-8");

Thank you,


To combine the answers of @Ricardo and @MarcoS

 DataInputStream dis = new DataInputStream(new FileInputStream("my-data-file.dat"));
 try {
     byte[] bytes = new byte[128];
     dis.readFully(bytes);
     // read some more.

 } finally {
     try {
        dis.close();
     } catch(IOException ignored) { }
 }


Why don't you use a FileInputStream? (http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html)

The read() method reads a byte, though it returns an int.


Have you tried with Data Streams?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜