简体   繁体   English

Android-读取输入流并将其另存为文件的最有效方法是什么?

[英]Android - Whats the most efficient way to read an inputstream and save as file?

I currently use the following to read a bluetooth inputstream and save it as a file. 我目前使用以下内容读取蓝牙输入流并将其另存为文件。 It works well with small files but then with larger files its creating a large byte array first. 它适用于较小的文件,但是适用于较大的文件,它首先会创建一个大字节数组。 Whats the most efficient way of doing this AND making sure that it reads the only the length specified, no more, no less? 什么是最有效的方法,并确保它仅读取指定的长度(不多也不少)?

    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);
        }
    }
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;
} 

Note that the above makes sure you don't write more that length bytes. 请注意,以上内容确保您不写更多的长度字节。 But it doesn't make sure you write exactly length bytes. 但这不能确保您确切地写出长度字节。 I don't see how you could do this without reading length bytes in memory, or reading length bytes and writing to a temp file, then writing the temp file to the final destination. 我看不到如何在不读取内存中的长度字节或读取长度字节并写入临时文件,然后将临时文件写入最终目标的情况下执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM