我有一种方法递归地将文件从一个文件夹复制到另一个文件夹,有效地创建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();
}
现在我的问题是,为什么它并不总是完全更新的目标文件夹。当我放弃进程并在稍后再次启动时,它不会将某些子文件夹和文件复制到目标。你看到代码有什么问题吗?
是因为你使用'onlyUpdates' == true?那些文件已被复制? –
@austinwernli:是的,它必须与此相关。不知何故,当前目录中的所有文件/文件夹都已被复制,但子文件夹或文件夹尚未复制时,递归将不会继续。不是100%确定原因,尽管 – BullyWiiPlaza