如何使用 apache.commons 从 FTP 下载文件,这是我一直在尝试做的事情:
ftp = new FTPClient();
ftp.connect("my.remote");
ftp.login("username", "password");
String ftpPath = "/my/file/file.data";
ftp.setFileTransferMode(FTPClient.BLOCK_TRANSFER_MODE);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println(ftp.mlistFile(ftpPath));
InputStream inputStream = ftp.retrieveFileStream(ftpPath);
if (inputStream == null) {
System.out.println("Error " + " " + ftp.getReplyCode() +
" " + ftp.getReplyString());
return;
}
但是它给了我一个错误,输出如下。如果我在同一台机器上使用 FileZilla,它确实可以工作
ype=file;Size=33130206;Modify=20170207225217;Perm=adfrw; file.data main
Error 500 500 Illegal PORT command
最佳答案
首先,你确定是FTP而不是FTPS吗? 其中一部分,尝试使用以下代码:
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
int reply;
ftp.connect(host,numPort); //if you have not port number, use only host
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("Error");
}
ftp.login(user, pwd);
ftp.setFileType(ftp.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
ftp.printWorkingDirectory(); //print workingdirectory
ftp.changeWorkingDirectory("/work"); //change directory
ftp.printWorkingDirectory();
FTPFile[] files1 = ftp.listFiles();
for (FTPFile file : files) {
String details = file.getName();
Calendar dateOfmyFile=file.getTimestamp();
boolean isaDir=false;
if (file.isDirectory()) {
details = "[" + details + "]";
isaDir=true;
}
else{
downloadFile(host+details, mylocalFilePath);
}
}
public void downloadFile(String remoteFilePath, String localFilePath) throws IOException {
FileOutputStream fos = null;
ftp.printWorkingDirectory();
try {
fos =new FileOutputStream(localFilePath);
ftp.retrieveFile(remoteFilePath,fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
关于java - Apache ftp.retrieveFileStream 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42141953/