1

私は現在、Bluetooth入力ストリームを読み取り、ファイルとして保存するために以下を使用しています。小さいファイルではうまく機能しますが、大きいファイルでは最初に大きいバイト配列を作成します。これを行う最も効率的な方法は何ですか?また、指定された長さだけを読み取り、それ以上でもそれ以下でもないことを確認しますか?

    public void getAndWrite(InputStream is, long length, String filename)
            throws IOException {

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read stream ");
        }

        // Write the byte array to file
        FileOutputStream fos = null;
        try {
            fos = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            Log.e(TAG, "Problem finding internal storage", e);
        }
        try {
            fos.write(bytes);
            fos.close();
        } catch (IOException e) {
            Log.e(TAG, "Problem writing file", e);
        }
    }
4

1 に答える 1

2
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int remaining = length;
int read = 0;
while (remaining > 0 
       && (read = in.read(buffer, 0, Math.min(remaining, bufferSize))) >= 0) {
   out.write(buffer, 0, read);
   remaining -= read;
} 

上記は、その長さのバイトを超えて書き込まないようにすることに注意してください。ただし、正確な長さのバイトを書き込むことは保証されません。メモリ内の長さバイトを読み取るか、長さバイトを読み取って一時ファイルに書き込み、次に一時ファイルを最終的な宛先に書き込むことなく、これを行う方法がわかりません。

于 2012-05-28T19:59:42.023 に答える