我想读取大文件(大于GB),并将其转换为字节数组,以便存储文件dB。
我面临的问题是,当我将文件转换为字节数组或读取文件时,我会得到Java堆内存运行时异常
我想知道在不使用更多内存的情况下读取文件并转换为字节数组的最好方法是什么
我已经用谷歌搜索过了,我发现IOUtils提供了更好的性能,但我试过它对我没有帮助。I使用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();
}
你能帮我把这个文件转换成最好的字节数组吗?
发布于 2021-05-17 07:23:30
当你说你想要写入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[]中,那么更好的选择是使用:
byte[] bArr = ByteBuffer.wrap(FileUtils.readFileToByteArray(new File(filePathToVeryLargeFileInGBs)));
https://stackoverflow.com/questions/58490013
复制相似问题