首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从fileInputStream转换byteArray

从fileInputStream转换byteArray
EN

Stack Overflow用户
提问于 2019-10-21 23:59:04
回答 1查看 68关注 0票数 2

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

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

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

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

代码语言:javascript
运行
复制
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();
}

你能帮我把这个文件转换成最好的字节数组吗?

EN

Stack Overflow用户

发布于 2021-05-17 07:23:30

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

代码语言:javascript
运行
复制
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[]中,那么更好的选择是使用:

代码语言:javascript
运行
复制
byte[] bArr = ByteBuffer.wrap(FileUtils.readFileToByteArray(new File(filePathToVeryLargeFileInGBs)));
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58490013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档