1

我目前使用以下内容来读取蓝牙输入流并将其保存为文件。它适用于小文件,但对于较大的文件,它首先创建一个大字节数组。这样做的最有效方法是什么,并确保它只读取指定的长度,不多也不少?

    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 回答