0

バイナリファイルを読み取るには、以下の方法を使用します。

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 バイト) を読み取るように見え、それらのデバイスとエミュレーターでアプリがクラッシュします。

ファイルをバイト単位で読み取るための最良の方法は何ですか?

4

2 に答える 2

3

Since you are always dealing with bytes, you should use an InputStream rather than an InputStreamReader.

Add the Javadoc says:

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

And the read() method reads a "character":

On the other hand, an InputStream represents an input stream of bytes:

public abstract int read() throws IOException

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

(And for kicks, here's a dated article about "buffered readers" in j2me)

于 2012-04-17T04:47:35.313 に答える
0

Nokia から直接見つけた最良の例

 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

于 2013-06-16T15:43:21.427 に答える