簡體   English   中英

Android-讀取輸入流並將其另存為文件的最有效方法是什么?

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

我目前使用以下內容讀取藍牙輸入流並將其另存為文件。 它適用於較小的文件,但是適用於較大的文件,它首先會創建一個大字節數組。 什么是最有效的方法,並確保它僅讀取指定的長度(不多也不少)?

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

請注意,以上內容確保您不寫更多的長度字節。 但這不能確保您確切地寫出長度字節。 我看不到如何在不讀取內存中的長度字節或讀取長度字節並寫入臨時文件,然后將臨時文件寫入最終目標的情況下執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM