今日、ユーティリティ クラスの 1 つで問題が発生しました。これはファイルのヘルパーであり、いくつかの静的ファイル コピー ルーチンが含まれています。以下は、テスト方法とともに抽出された関連する方法です。
問題は、setLastModified 呼び出しが失敗して、false が返されることがあるということです。
私の PC (Windows 7、最新の Java) では、「setLastModified failed」というメッセージが表示されることがあります (1000 回中約 25 回)。
FileChannel.close 呼び出しを削除することで問題を回避しましたが、それが正しい解決策であっても、なぜこれが起こっているのかを理解したいと思っています。
他の誰かが同じ問題を抱えていますか?
private void testCopy() throws FileNotFoundException, IOException {
File src = new File("C:\\Public\\Test-Src.txt");
File dst = new File("C:\\Public\\Test-Dst.txt");
for (int i = 0; i < 1000; i++) {
copyFile(src, dst);
}
}
public static void copyFile(final File from, final File to) throws FileNotFoundException, IOException {
final String tmpName = to.getAbsolutePath() + ".tmp";
// Copy to a .tmp file.
final File tmp = new File(tmpName);
// Do the transfer.
transfer(from, tmp);
// Preserve time.
if (!tmp.setLastModified(from.lastModified())) {
System.err.println("setLastModified failed!");
}
// In case there's one there already.
to.delete();
// Rename it in.
tmp.renameTo(to);
}
public static void transfer(final File from, final File to) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(from);
out = new FileOutputStream(to);
transfer(in, out);
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
}
public static void transfer(final FileInputStream from, final FileOutputStream to) throws IOException {
FileChannel srcChannel = null;
FileChannel dstChannel = null;
//try {
srcChannel = from.getChannel();
dstChannel = to.getChannel();
srcChannel.transferTo(0, srcChannel.size(), dstChannel);
//} finally {
// if (null != dstChannel) {
// dstChannel.close();
// }
// if (null != srcChannel) {
// srcChannel.close();
// }
}
}
編集:を閉じるStreams
と.FileChannel
FileChannel
Stream