私は現在、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);
}
}