OGeek|极客世界-中国程序员成长平台

标题: java - 如何在没有 OutOfMemory 错误的情况下从 FileInputStream 获取字节数组 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-9 06:50
标题: java - 如何在没有 OutOfMemory 错误的情况下从 FileInputStream 获取字节数组

我有一个包含 200MB 数据的 FileInputStream。我必须从输入流中检索字节。

我正在使用下面的代码将 InputStream 转换为字节数组。

private byte[] convertStreamToByteArray(InputStream inputStream) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        int i;
        while ((i = inputStream.read()) > 0) {
            bos.write(i);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bos.toByteArray();
}

在将如此大的数据转换为字节数组时,我遇到了 OutOfMemory 异常。

请告诉我任何将 InputStream 转换为字节数组的可能解决方案。



Best Answer-推荐答案


为什么要将 200MB 的文件保存在内存中?你打算用字节数组做什么?

如果要将其写入 OutputStream,请先准备好 OutputStream,然后一次读取 InputStream 一个 block ,然后将 block 写入 OutputStream。你永远不会在内存中存储超过 block 。

例如:

     public static void pipe(InputStream is, OutputStream os) throws IOException {

        int read = -1;
        byte[] buf = new byte[1024];

        try {
            while( (read = is.read(buf)) != -1) {
                os.write(buf, 0, read);
            }
        }
        finally {
            is.close();
            os.close();
        }
    }

此代码将采用两个流并将一个流传输到另一个。

关于java - 如何在没有 OutOfMemory 错误的情况下从 FileInputStream 获取字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15825865/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://www.ogeek.cn/) Powered by Discuz! X3.4