1
我試圖將FTP路徑中的所有文件下載到本地系統。但下載的文件在0 KB。會有什麼問題。請幫我找到錯誤。 (文件類型爲* .zip,* .pdf,* .xml)Ftp下載文件大小爲0 KB
在此先感謝。
package ConnectFTP;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FTPDownloader {
FTPClient ftp = null;
public FTPDownloader(String host, String user, String pwd) throws Exception {
ftp = new FTPClient();
int reply;
ftp.connect(host);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new Exception("Exception in connecting to FTP Server");
}
ftp.login(user, pwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
}
public void downloadFile(String remoteFilePath, String localFilePath) {
try (FileOutputStream fos = new FileOutputStream(localFilePath)) {
this.ftp.retrieveFile(remoteFilePath, fos);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void disconnect() {
if (this.ftp.isConnected()) {
try {
this.ftp.logout();
this.ftp.disconnect();
} catch (IOException ioe) {
}
}
}
public static void main(String[] args) {
try {
FTPDownloader ftpDownloader =
new FTPDownloader("192.168.3.1", "Adminuser", "password");
ftpDownloader.listFolders();
System.out.println("File downloaded successfully");
ftpDownloader.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public void listFolders() {
try {
String ftpBasePath = "dev";
FTPFile[] fileList = ftp.listDirectories("/" + ftpBasePath);
for (FTPFile file : fileList) {
listFiles(file.getName());
}
} catch (IOException ex) {
Logger.getLogger(FTPDownloader.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void listFiles(String path) {
try {
FTPFile[] fileList = ftp.listFiles(path);
for (FTPFile file : fileList) {
String currentFileName = file.getName();
String localPath = "E:\\FTPFiles\\"+currentFileName;
try (FileOutputStream fos = new FileOutputStream(localPath)) {
this.ftp.retrieveFile(currentFileName, fos);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} catch (IOException ioe) {
Logger.getLogger(FTPDownloader.class.getName()).log(Level.SEVERE, null, ioe);
}
}
}
您看到的任何錯誤? – Santosh
沒有找到錯誤。 – Nitin
從FTPDownloader中移除'throws Exception'並在方法內部使用'try-catch'。這會告訴你什麼是錯的。 – user2339071