java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)中的java.lang.OutOfMemoryError?

时间:2017-07-07 06:09:19

标签: android out-of-memory

我在将文件上传到Google驱动器时遇到此问题,我正在将录制的音频上传到Google驱动器,此时此异常正在发生

用于在文件中编写内容的代码

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

行中出现异常

请帮我解决这个错误。

2 个答案:

答案 0 :(得分:1)

您正在获取OOM,因为在将其写入google驱动器outputStream之前,您尝试将完整文件读入内存。该文件可能太大而无法存储在内存中。这样你需要逐个编写它。使用这种方法很容易实现:

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

该方法将返回复制的字节数。

答案 1 :(得分:1)

首先写入ByteArrayOutputStream意味着完整的文件将最终出现在JVM的堆中。这取决于文件大小和堆大小,这可能是不可能的,因此是例外。如果您不需要ByteArrayOutputStream其他任何内容,只需直接写入outputStream

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

P.S。:如果参考文献很快超出范围,则无需将参考文献归零......