【问题标题】:Convert byteArray from fileInputStream从 fileInputStream 转换 byteArray
【发布时间】:2019-10-21 15:59:03
【问题描述】:

我想读取大文件(超过 GB)并将其转换为字节数组以存储文件 dB。

我面临的问题是当我将文件转换为字节数组或读取文件时,我得到 Java 堆内存运行时异常

我想知道在不使用更多内存的情况下读取文件并转换为字节数组的最佳方法是什么

我用谷歌搜索发现 IOUtils 提供了更好的性能,但我尝试过它对我有帮助。我使用 java 8

private void readFile() throws IOException {

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("C:\test.mp4")
            byte[] bytes = IOUtils.toByteArray(fileInputStream);
            Base64 codec = new Base64();
            byte[] decoded = codec.encode(bytes);

                                            fileInputStream.close();
}

你能帮忙用最好的方法将该文件转换为字节数组吗?

【问题讨论】:

  • 如果要将文件字节作为字节存储到 DB 列中,为什么要在 Base64() 中对其进行编码?我错过了什么吗?
  • @IoannisBarakos 我想做那个。我在 byte[] bytes = IOUtils.toByteArray(fileInputStream); 中出现堆内存错误
  • 读取内存中的整个文件时会出现 OOM 错误(codec.encode(bytes))。你不应该那样做。您的数据库表应该有一个 BLOB 列用于存储文件二进制数据。您首先插入一个空 blob,然后您应该将 Stream 获取到这个空 blob,并开始将字节从 FileInputStream 处理到 Blob 输出流。您可以阅读:docs.oracle.com/cd/B19306_01/java.102/b14355/…

标签: java spring performance java-8 fileinputstream


【解决方案1】:

当您说要写入 db 时,请避免读取内存中的数组。 使用 setCharacterStream 直接更新到 db。

Connection conn = //... initialize connection
PreparedStmt stmt = null;
try {
    stmt = conn.prepareStatement(this.insertQuerySql);
    stmt.setLong(1, varLong); 
    stmt.setString(2, varString);
    stmt.setString(3, varString2);
    File file = new File(filePathToVeryLargeFileInGBs);
    FileReader fileReader = new FileReader(file);
    pstmt.setCharacterStream(4, fileReader, Files.size(Paths.get(filePathToVeryLargeFileInGBs);
    pstmt.executeUpdate();
} catch(Exception e) {
    System.err.println(e);
    e.printStackTrace();
} finally {
    if (stmt != null ) { 
        stmt.close();
    }   
    if (conn != null ) { 
        try {
            conn.close();
        }   
        catch(Exception e2) {
            e2.printStackTrace();
        }   
    }   
}

如果你必须把它读成一个字节[] 那么更好的选择是使用:

byte[] bArr = ByteBuffer.wrap(FileUtils.readFileToByteArray(new File(filePathToVeryLargeFileInGBs)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多