我有将.zip文件从一个位置复制到另一个位置的代码。它按预期工作。 我想检查文件夹中是否存在复制的文件。如果是,它应该继续其他复制文件。
我相信我的逻辑是正确的,但我不确定我哪里出错了,因为它不会检查文件是否存在
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class ZipFileMover
{
public void findFiles(File root, int depth)
throws IOException
{
File[] listOfFiles = root.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
String iName = listOfFiles[i].getName();
if (listOfFiles[i].isFile())
{
if (iName.endsWith(".zip"))
{
for (int j = 0; j < depth; j++)
{}
System.out.println("Files: " + iName);
File dest = new File(
"C:\\Users\\somename\\Documents\\Development\\ZipFiles\\"
+ iName);
String path = "C:\\Users\\somename\\Documents\\Development\\ZipFiles\\"
+ iName;
// C:\Users\somename\Documents\Development\
// System.out.println("ROOT + iNAME : " + (root + "\\" + iName));
// //C:\Users\somename\Documents\Development\filename.zip
boolean check = new File(dest, iName).exists();
System.out.println(check);
if ((root + "\\" + iName).equals(path))
{
continue;
}
else
{
if (check == true)
{
System.out.println(
"Skipped file " + iName + " it already exsits in folder.");
continue;
}
else
{
System.out.println();
System.out.println("Copying file " + iName);
System.out.println();
FileUtils.copyFile(new File(root + "\\" + iName), dest);
}
}
}
}
else if (listOfFiles[i].isDirectory())
{
for (int j = 0; j < depth; j++)
findFiles(listOfFiles[i], depth + 1);
}
}
}
}
答案 0 :(得分:2)
确保使用IDE的调试功能,它将帮助您确定逻辑错误所在的位置。
附注:不要添加更多内容而不是你必须添加更多内容会使代码难以理解,这应该简化它。
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class ZipFileMover
{
static String outputPath = "C:\\Users\\somename\\Documents\\Development\\ZipFiles\\";
public void findFiles(File root, int depth)
throws IOException
{
File[] listOfFiles = root.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
String iName = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && iName.endsWith(".zip"))
{
System.out.println("Files: " + iName);
File dest = new File(outputPath + iName);
if (dest.exists())
{
System.out.println(
"Skipped file " + iName + " it already exsits in folder.");
continue;
}
else if ((root + "\\" + iName).equals(dest))
{
continue;
}
else
{
System.out.println();
System.out.println("Copying file " + iName);
System.out.println();
FileUtils.copyFile(listOfFiles[i], dest);
}
}
else if (listOfFiles[i].isDirectory())
{
for (int j = 0; j < depth; j++)
findFiles(listOfFiles[i], depth + 1);
}
}
}
}
答案 1 :(得分:1)
boolean check = dest.exists();