我正在尝试使用 FTP 从服务器下载文件,如果该文件在远程服务器中可用,则 Java 代码可以工作,但如果特定文件在远程服务器中不可用,则会使用相同的文件名创建新文件在本地。我怎样才能避免这种情况?
我正在尝试在下载之前检查特定文件的属性,例如上次修改时间、文件创建时间等,我使用了 MLST,但遇到了类型转换问题..!!
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FTPDownloadFileDemo {
public static void main(String[] args) {
String server = "www.myserver.com";
int port = 21;
String user = "user";
String pass = "pass";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// APPROACH #1: using retrieveFile(String, OutputStream)
String remoteFile1 = "/test/video.mp4";
File downloadFile1 = new File("D:/Downloads/video.mp4");
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
if (success) {
System.out.println("File #1 has been downloaded successfully.");
}
outputStream2.close();
inputStream.close();
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
最佳答案
retrieveFile() 方法始终写入本地文件,无论远程文件是否存在。相反,您可以使用 retrieveFileStream()并检查回复代码。
一个handy list of FTP reply codes可从维基百科获取。如果收到550,则表示该文件不存在。
最后,您需要使用completePendingCommand()完成交易并获得FileOutputStream写入文件。
InputStream inputStream = ftpClient.retrieveFileStream(remoteFile1);
int returnCode = ftpClient.getReplyCode();
if (inputStream == null || returnCode == 550) {
System.out.println("Remote file does not exist");
} else {
ftpClient.completePendingCommand();
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
OutputStream outputStream = new FileOutputStream(downloadFile1);
outputStream.write(buffer);
outputStream.close();
}
关于java - FTP 下载期间正在创建新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48653364/