How to check if file exist when downloading from FTP
12,379
Solution 1
You should check for existence using java.io.File.exists
and java.io.File.isFile()|isDirectory()
.
Solution 2
Maybe it will be useful to somebody with same problem. I made program by this method:
package javaapplication2;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.*;
public class DLFile {
public static void saveZIP() throws Exception {
FTPClient client = new FTPClient();
FileOutputStream new_file = null;
String server = "server";
String user = "user";
String pass = "pass";
String name = "";
String downloadFolder = "download_folder";
Boolean exists = null;
int i=0;
int j=0;
client.connect(server);
client.login(user,pass);
client.changeWorkingDirectory("/rtr/");
//read ftp content
String[] names = client.listNames();
File folder = new File(downloadFolder);
String[] filename = folder.list();
for (;i<names.length;i++) {
name = names[i];
exists=false;
if (name.contains(".zip")) {
if (filename.length == 0) {
new_file = new FileOutputStream(downloadFolder + name);
client.retrieveFile(name, new_file);
j++;
exists=true;
} else {
//CHECK IF FILE EXISTS
if (!new File(downloadFolder + name).exists()) {
new_file = new FileOutputStream(downloadFolder + name);
client.retrieveFile(name, new_file);
j++;
exists=true;
}
}//else
}//if contains .zip
}//for
if (exists = true) {
System.out.println("Downloading ZIP files: Downloaded " + j + " files");
} else System.out.println("Downloading ZIP files: Files already exist.");
client.logout();
}
}
Author by
Igor
Updated on June 14, 2022Comments
-
Igor almost 2 years
I'm downloading from FTP server and I don't know exactly how to check if file already exist. What I want to do is that I retrieve filname from FTP server and then compare it with all files in folder. If file already exists then it compares next FTP filename with all files in folder and so on. I already did comparison and it's working if all files from folder have same name as files on FTP server but if I add some older file then it downloads all files once again and I don't want that.
Here is my scratch code:
String[] names = client.listNames(); File folder = new File("c:\\test\\RTR_ZIP\\"); String[] filename = folder.list(); for (;i<names.length;i++) { name = names[i]; exists=false; if (name.contains(".zip")) { if (filename.length == 0) { new_file = new FileOutputStream("C:\\test\\RTR_ZIP\\" + name); client.retrieveFile(name, new_file); j++; exists=true; } else { for (;k<filename.length;k++) { name = names[i]; i++; name1=filename[k]; // CHECK IF FILE EXISTS if (!name.equals(name1)) { new_file = new FileOutputStream("C:\\test\\RTR_ZIP\\" + name); client.retrieveFile(name, new_file); j++; exists=true; } } }//else }//if contains .zip }//for
Thanks in advance.