从Android上的二进制文件中读取

时间:2011-04-20 19:02:10

标签: java android matlab

我有一些使用Matlab保存到文件中的数据。我已将这些数据保存在Matlab中,如下所示:

fwrite(fid,numImg2,'integer*4');
fwrite(fid,y,'integer*4');
fwrite(fid,imgName,'char*1');
fwrite(fid,a,'integer*4');        
fwrite(fid,img.imageData,'double'); 

我使用以下代码将此数据读回Matlab

fread(fid,1,'integer*4');// Returns numImg2
fread(fid,1,'integer*4');// Returns y which is the number of cha rectors in the image name,     i use in the following line to read the image name, say for example if the image name is 1.jpg, then using the following will return the image name
fread(fid,5,'char*1');
fread(fid,1);
etc...

我希望能够在Android手机上阅读这些数据。这是我目前的代码。

DataInputStream ds = new DataInputStream(new FileInputStream(imageFile));
                //String line;
                // Read the first byte to find out how many images are stored in the file.
                int x = 0;
                byte numberOfImages;
                int numImages = 0;
                while(x<1)
                {
                    numberOfImages = ds.readByte();
                    numImages = (int)numberOfImages;
                    x++;
                }

                int lengthName = 0;
                String imgName = "";
                for(int y=1; y<=numImages; y++)
                {
                    lengthName = ds.readInt();
                    byte[] nameBuffer = new byte[lengthName];
                    char[] name = new char[lengthName];
                    for(int z = 1; z<=5;z++)
                    {
                        nameBuffer[z-1] = ds.readByte();
                        //name[z-1] = ds.readChar();
                    }
                    imgName = new String(nameBuffer);
                    //imgName = name.toString();
                }

                text.append(imgName);

我似乎无法从二进制文件数据中将图像名称检索为字符串。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我不确定它会起作用但是无论如何:

byte[] nameBuffer = new byte[lengthName];
if(ds.read(nameBuffer) != lengthName) {
    // error handling here
    return;
}
imgName = new String(nameBuffer, "ISO-8859-1");