在j2me中从二进制文件读取到字节数组

时间:2012-04-17 04:40:40

标签: file java-me

我使用以下方法读取二进制文件:

public void readFile()
{
    try
    {
        Reader in = new InputStreamReader( this.getClass().getResourceAsStream( this.fileName));
        int count = (in.read() * 0xFF) + in.read();
        int heights = in.read();

        this.shapes = new int[count][];
        for(int ii = 0;ii<count;ii++)
        {
            int gwidth = in.read();
            int[] tempG = new int[gwidth * heights];
            int len = (in.read() * 0xff) + in.read();
            for(int jj = 0;jj<len;jj++)
            {
                tempG[top++] = in.read() * 0x1000000;
            }
            this.shapes[ii] = tempG;
        }
        in.close();

    }catch(Exception e){}
}

它在netbeans模拟器和一些设备中运行良好,但在某些设备和kemulator中似乎in.read(),读取一个char(两个字节),它会导致我的应用程序在这些设备上崩溃和模拟器。

以字节为单位读取文件的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

由于您始终处理字节,因此应使用InputStream而不是InputStreamReader

添加Javadoc说:

  

InputStreamReader是从字节流到字符流的桥接器:它使用指定的字符集读取字节并将其解码为字符。它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。

read()方法读取“字符”:

另一方面,InputStream表示 bytes 的输入流:

  

public abstract int read()抛出IOException

     

从输入流中读取下一个数据字节。值字节作为int返回,范围为0到255.如果没有字节可用,因为已到达流的末尾,则返回值-1。此方法将阻塞,直到输入数据可用,检测到流的末尾或抛出异常。

(对于踢球,这里是dated article about "buffered readers" in j2me

答案 1 :(得分:0)

我可以直接从诺基亚找到最好的例子

 public Image readFile(String path) {
        try {
            FileConnection fc = (FileConnection)Connector.open(path, Connector.READ);
            if(!fc.exists()) {
                System.out.println("File doesn't exist!");
            }
            else {
                int size = (int)fc.fileSize();
                InputStream is = fc.openInputStream();
                byte bytes[] = new byte[size];
                is.read(bytes, 0, size);
                image = Image.createImage(bytes, 0, size);
            }

        } catch (IOException ioe) {
            System.out.println("IOException: "+ioe.getMessage());
        } catch (IllegalArgumentException iae) {
            System.out.println("IllegalArgumentException: "+iae.getMessage());
        }
        return image;
   }

http://www.developer.nokia.com/Community/Wiki/How_to_read_an_image_from_Gallery_in_Java_ME

相关问题