Avión Avión - 26 days ago 7
Java Question

Speeding up reading from InputStream and writing with FileOutputStream

I'm reading some blob's from a column of a databse and them saving to a file using

FileOutputStream
.

This is my code:

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);
}


The thing is that this is extremelly slow. I need to convert more than 58225 items and it can take up to 24h.

Can someone tell me how can I make that read-from-InputStreamwrite-to-FileOutputStream somehow faster?

Thanks in advance.

Answer

Read and write using a buffer.

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);
}

EDIT: See DwB's answer for an alternative to rolling your own buffer...

EDIT: Also @Nicolas Filotto has a better suggestion too...