Mani Mani - 1 month ago 6
Java Question

Copying file locally from one location to another and checking if file exists

I have the code which copies the .zip files from one location to another. It works as expected.
I want to check if the copied file exists in the folder. If it does it should continue else copy the file.

I believe my logic is correct but I am not sure where I am going wrong because it does not check if file exists or not

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);
}
}
}
}

Answer
boolean check = dest.exists();