Androidで高速なファイルコピー
目次
Android(Java)でファイルコピーをするのには、単純に Input から読んで、それをそのまま Output に書き出す方法が単純です。しかし FileChannel を使用するとシンプルかつ高速にファイルをコピーすることができます。
ただし FileChannel を使用したコピーでは一度にコピーできるサイズが 2GB に制限されるという仕様があるので、どこまでコピーしたか確認しながらコピーするように修正しました。
public static boolean copy(File src, File dst) {
boolean result = false;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(src);
outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
long pos = 0;
while (pos < inChannel.size()) {
pos += inChannel.transferTo(pos, inChannel.size(), outChannel);
}
result = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inStream != null) inStream.close();
if (outStream != null) outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if ((! result) && dst.exists()) dst.delete();
return result;
}
純粋に Java でのコピーならが、Files.copy()を使用するのが一番簡単です。