2017-07-07 3 views
0
私がGoogleドライブにファイルをアップロードするには、この問題に直面しています

、私はこの例外は、ファイルのコンテンツを書き込むために使用java.lang.OutOfMemoryError at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)?

コードを発生している時の駆動グーグルへの音声記録アップロードしています

     OutputStream outputStream = result.getDriveContents().getOutputStream(); 
        FileInputStream fis; 
        try { 
         fis = new FileInputStream(file); 
         ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
         byte[] buf = new byte[1024]; 
         int n; 
         while (-1 != (n = fis.read(buf))) 
          baos.write(buf, 0, n); 
         byte[] photoBytes = baos.toByteArray(); 
         outputStream.write(photoBytes); 

         outputStream.close(); 
         outputStream = null; 
         fis.close(); 
         fis = null; 

         Log.e("File Size", "Size " + file.length()); 

        } catch (FileNotFoundException e) { 
         Log.v("EXCEPTION", "FileNotFoundException: " + e.getMessage()); 
        } catch (IOException e1) { 
         Log.v("EXCEPTION", "Unable to write file contents." + e1.getMessage()); 
        } 

例外は、行 `baos.write(buf、0、n);で発生します。

GoogleドライブOutputStreamに書き込む前にメモリに完全なファイルを読み取ろうとするのであなたがOOMを得ているこのerror.`に

+0

はなぜ書くのですか'outputStream'に直接書き込むのではなく、' ByteArrayOutputStream'に渡しますか?ファイルサイズによっては、ファイル全体をメモリに保存することができない場合があります。 –

+0

@ piet.t詳細を説明し、回答を投稿します –

答えて

1

最初にByteArrayOutputStreamに書き込むと、完全なファイルがJVMのヒープに格納されます。ファイルサイズとヒープサイズによっては、これは可能ではない可能性があります。そのため例外です。あなただけoutputStreamに直接書き込み、何のためにByteArrayOutputStreamを必要としない場合:

OutputStream outputStream = result.getDriveContents().getOutputStream(); 
FileInputStream fis; 
try { 
    fis = new FileInputStream(file); 
    byte[] buf = new byte[1024]; 
    int n; 
    while (-1 != (n = fis.read(buf))) 
     outputStream.write(buf, 0, n); 


} catch (FileNotFoundException e) { 
    Log.v("EXCEPTION", "FileNotFoundException: " + e.getMessage()); 
} catch (IOException e1) { 
    Log.v("EXCEPTION", "Unable to write file contents." + e1.getMessage()); 
} finally { 
    outputStream.close(); 
    fis.close(); 
    Log.e("File Size", "Size " + file.length()); 
} 

PS:彼らはすぐにスコープの外に出た場合の参照をゼロにすることは必要ではないはず...

+0

あなたの答えは働きます...ありがとう –

1

を解決するためにどのように私を助けてください。ファイルが大きすぎてメモリに格納できない可能性があります。このように、あなたはパートごとにそれを書く必要があります。このメソッドを使用すると簡単に達成できます。

private static final int BUFFER_SIZE = 1024; 

    public static long copy(InputStream from, OutputStream to) 
     throws IOException { 
    byte[] buffer = new byte[BUFFER_SIZE]; 
    long total = 0; 
    while (true) { 
     int r = from.read(buffer); 
     if (r == -1) { 
     break; 
     } 
     to.write(buffer, 0, r); 
     total += r; 
    } 
    return total; 
    } 

このメソッドはコピーされたバイト数を返します。

関連する問題