我有一个函数可以使用FileInputStream. 它在我的 IDE 中运行良好,但是当通过可执行文件独立运行时jar,它抛出Exception in thread "main" java.lang.OutOfMemoryError: Java heap space。我正在读取字节数组中的这个大文件,以将其作为 Blob 存储在目标数据库中。我无法控制 Blob 的存储方式,我只能访问存储过程来插入 Blob。有没有办法在不将整个文件加载到内存的情况下读取和写入数据块?
将文件转换为字节数组的函数 -
private byte[] getBytesFromFile(Path path) throws IOException {
FileInputStream fis = new FileInputStream(path.toFile());
byte[] bytes = new byte[(int) path.toFile().length()];
int read = 0;
int offset = 0;
while(offset < bytes.length && (read = fis.read(bytes, offset, bytes.length - offset)) >= 0 ){
offset += read;
}
fis.close();
return bytes;
}
这是使用存储过程调用将字节数组存储到 db 的代码
private void storeFileToDb(Connection connection, int fileId, String fileName, String fileType, byte[] fileBytes) throws SQLException {
//
String storedProcedure = "{call SP(?,?,?,?,?) }";
CallableStatement callableStatement = connection.prepareCall(storedProcedure);
callableStatement.setInt(1, fileId);
callableStatement.setString(2, fileName);
callableStatement.setString(3, fileType);
Blob fileBlob = connection.createBlob();
fileBlob.setBytes(1, fileBytes);
callableStatement.setBlob(4, fileBlob);
callableStatement.registerOutParameter(5, OracleTypes.NUMBER);
callableStatement.execute();
fileBlob.free(); // not entirely sure how this helps
//callableStatement.close();
}
12345678_0001
白板的微信
相关分类