I am trying to upload a file to two different directories. But somehow it copies the file to one directory , but fails to copy in second directory.
My src directory for file is something like this
C:\path\to\temp
And my destination directories are like this
C:\path\to\destination\1 & C:\path\to\destination\2
directories 1 and 2 are getting created on the fly.
This is what I am using in my code
public final static boolean move(String src, String dest, boolean createDestDir, boolean overwrite) {
try{
if(src == null || src.length() == 0 || dest == null || dest.length() == 0){
return false;
}
File srcFile = new File(src);
if(srcFile.isFile() == false){
return false;
}
String destPath = path(dest);
String destFileName;
if (destPath.equals(dest)) {
destFileName = srcFile.getName();
} else {
destFileName = name(dest);
}
File destDir = new File(destPath);
if (destDir.exists() == false) {
if (createDestDir == false) return false;
if (destDir.mkdirs() == false) {
return false;
}
}
File destFile = new File(destPath + destFileName);
if (destFile.exists()) {
if (overwrite == false) return false;
if (destFile.delete() == false) {
return false;
}
}
return srcFile.renameTo(destFile);
}
}
During my loop srcFile.isFile() is failing second time, it works first time, but fails second time.
The
mkdirsmethod creates any missing parent directories in the filepath. Eg. if the destination location is C:\some\path\to\file\, then if you callmkdirs, it will check that C:\some exists, then C:\some\path, and so on. If the path does not exist, it will create that folder and keep going. When it finishes, it will only return true if it had to create any folders. If the directory structure exists, it will return false.In your code, you have this:
I’m not sure why you go through such a convoluted way of creating the directory structure. Instead of the whole
createDestDirvariable (which I suspect isfalsewhen it should be true), you could just call themkdirs()method. There is no hard calling that method if the directory structure is already in place.Then in your next bit of code, you check if the file already exists on the file system. If it does exist, and you haven’t set the
overwriteboolean totrue, then you try to delete the file. But at no point do you callcreateNewFile(). You never actually create the file on the file system.Try replacing the above code with this:
This will create the destination directory if necessary, check for the existance of the file (and delete it if permissible and necessary), and then create the file at that location.
Also you should check to make sure that
destPathends with a file separator — eg. “/” in Linux/Unix or “\” in Windows — or elsedestPath + destFileNamewill give you something wonky.