我有一種方法遞歸地將文件從一個文件夾複製到另一個文件夾,有效地創建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