I am copying files using BufferedInputStream . I copy byte[] in loop. This is quite slow for big files.
I saw the FileChannel structure. I tried using this also. I want to know if FileChannel is better than using IOSTreams. During my testings, i am not able to see a major performance improvement.
Or is there any other better solution.
My requirement is modify first 1000 bytes of src file and copy to target, copy the rest of the byte of the src file to target file.
With fileChannel
private void copyFile(File sourceFile, File destFile,byte[] buffer,int srcOffset, int destOffset) {
try {
if (!sourceFile.exists()) {
return;
}
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
source.position(srcOffset);
destination = new FileOutputStream(destFile).getChannel();
destination.write(ByteBuffer.wrap(buffer));
if (destination != null && source != null) {
destination.transferFrom(source, destOffset, source.size()-srcOffset);
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
using I/O stream
while ((count = random.read(bufferData)) != -1) {
fos.write(bufferData, 0, count);
}
I believe that performance cannot be noticeably increased since hard disk/sd-card speed is probably the bottleneck.
However it might help to create a background task that does the copying.
This is not realy faster but it feels faster because you donot have to wait for the completion of the copy operation.
This solution only works if your app does not need the result immediately after starting.
For details see AsyncTask