2016-11-11 78 views
0

我正在读取数据库列中的一些blob,并使用FileOutputStream将它们保存到文件中。加速从InputStream中读取并使用FileOutputStream进行写入

这是我的代码:

InputStream binaryFile = rs_ivol.getBinaryStream("BLOB_COLUMN_FROM_BY_DB"); 
FileOutputStream outputFile = new FileOutputStream(myoutpath); 
int aux = 0; 
while ((aux = binaryFile.read()) != -1) 
{ 
    outputFile.write(aux); 
} 

的事情是,这是extremelly缓慢。我需要转换超过58225件物品,最多可能需要24小时。

有人能告诉我怎样可以使读从-的InputStream写入到FileOutputStream中莫名其妙更快?

在此先感谢。

回答

2

使用缓冲区读写。

InputStream binaryFile = rs_ivol.getBinaryStream("BLOB_COLUMN_FROM_BY_DB"); 
FileOutputStream outputFile = new FileOutputStream(myoutpath); 
int aux = 0; 
byte[] buffer = new byte[1024]; 
while ((aux = binaryFile.read(buffer)) > 0) 
{ 
    outputFile.write(buffer, 0, aux); 
} 

编辑: 见DWB的答案滚动轴承的替代自己的缓冲...

编辑: 也@Nicolas Filotto有更好的建议太...

+0

谢谢,现在*更快*。如果我增加缓冲区,它会更快? –

+0

@Avion:不多。性能瓶颈可能是与数据库的连接,即从数据库中读取BLOB。 –

+0

不要忘记关闭流 –

1

假设你有的Java 7或更高版本,你不想重新发明轮子,可以考虑使用Files.copy(InputStream in, Path target, CopyOption... options)为未来:

try (InputStream binaryFile = rs_ivol.getBinaryStream("BLOB_COLUMN_FROM_BY_DB")) { 
    Files.copy(binaryFile, Paths.get(myoutpath), StandardCopyOption.REPLACE_EXISTING); 
}