我正在从FTP服务器下载文件,但我不知道如何检查文件是否已经存在.我想做的是从FTP服务器检索filname,然后将其与文件夹中的所有文件进行比较.如果文件已经存在,则将下一个FTP文件名与文件夹中的所有文件进行比较,依此类推.
我已经进行了比较,如果文件夹中的所有文件都与FTP服务器上的文件具有相同的名称,则可以正常工作,但是如果我添加了一些旧文件,则它将再次下载所有文件,而我不希望这样做.
这是我的暂存代码:
String[] names = client.listNames();
File folder = new File("c:\test\RTR_ZIP\");
String[] filename = folder.list();
for (;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
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
提前致谢.
最佳答案
如果您的ftp服务器支持XCRC命令,则可以比较本地和远程文件的校验和(CRC32).
您可以迭代文件夹中的所有文件,并将其crc与本地文件进行比较.
import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTPClient;
public class DownloadFile {
private FTPClient client = new FTPClient();
public void connect() throws SocketException, IOException {
client.connect("127.0.0.1");
client.login("user", "password");
}
public boolean hasXCRCSupport() throws IOException {
client.sendCommand("feat");
String response = client.getReplyString();
Scanner scanner = new Scanner(response);
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains("XCRC")) {
return true;
}
}
return false;
}
public boolean isSameFile() throws IOException {
if(hasXCRCSupport()) {
File file = new File("D:/test.txt");
String localCRC = Integer.toHexString((int) FileUtils.checksumCRC32(file)).toUpperCase();
client.sendCommand("XCRC /test.txt");
String response = client.getReplyString().trim();
System.out.println(response);
if(response.endsWith(localCRC)) {
return true;
}
}
return false;
}
public void logout() throws IOException {
client.logout();
}
public static void main(String[] args) throws SocketException, IOException {
DownloadFile downloadFile = new DownloadFile();
downloadFile.connect();
if(downloadFile.isSameFile()) {
System.out.println("remote file is same as local");
}
downloadFile.logout();
}
}