我有一个方法,可以将文件从一个文件夹递归复制到另一个文件夹,有效地创建1:1副本。它应该做的另一个转折只是复制目的地不存在的文件和已经修改过的文件。这是我为此写的代码:
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public static void copy(File source, File destination) throws IOException
{
copy(source, destination, true);
}
private static void copy(File source, File destination, boolean onlyUpdates)
throws IOException
{
if (source.isDirectory())
{
if (!destination.exists())
{
createFolder(destination);
}
String[] sourceChildren = source.list();
for (int sourceChildrenIndex = 0; sourceChildrenIndex < sourceChildren.length; sourceChildrenIndex++)
{
File currentSource = new File(source,
sourceChildren[sourceChildrenIndex]);
File currentDestination = new File(destination,
sourceChildren[sourceChildrenIndex]);
copy(currentSource, currentDestination, onlyUpdates);
}
} else
{
if (onlyUpdates)
{
if (isNewer(source, destination) && isDifferent(source, destination))
{
copyFile(source, destination);
}
}
}
}
private static boolean isDifferent(File source, File destination)
{
return source.length() != destination.length();
}
private static boolean isNewer(File source, File destination)
{
return source.lastModified() > destination.lastModified();
}
private static void copyFile(File source, File destination)
throws IOException
{
try
{
Files.copy(source.toPath(), destination.toPath(),
StandardCopyOption.REPLACE_EXISTING);
} catch (FileSystemException e)
{
e.printStackTrace();
}
}
private static void createFolder(File destination)
{
destination.mkdir();
}
现在我的问题是为什么它并不总是完全更新目标文件夹。当我中止该过程并稍后再次启动它时,它不会将一些子文件夹和文件复制到目标。你看到代码有什么问题吗?
答案 0 :(得分:0)
您需要比较文件的大小,而不仅仅是它们的时间戳。如果你的程序中止了飞行,那么部分副本将被遗忘。