项目中需要从ftp服务器上下载zip文件,然而下载后的ZIP文件打不开,提示损坏。
解决方法是在添加 ftp.setFileType(FTP.BINARY_FILE_TYPE);而且必须在登录之后进行设置才会起到作用。
FTP下载ZIP文件
代码如下:
package service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
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 FtpDownTest {
public static final String DOWNLOAD_URL = "###";//FTP服务器URL
public static final String USER_NAME = "####";
public static final String PASSWORD = "###";
public static final String REMOTE_PATH = "####";//登录之后跳转页面URL
public static final String lOCAL_PATH = "E:\\CHD\\static";
public static void main(String[] args) {
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(DOWNLOAD_URL);
ftp.setControlEncoding("UTF-8");
System.out.println("===ftp connect===");
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(USER_NAME, PASSWORD);//登录
ftp.setFileType(FTP.BINARY_FILE_TYPE); //登录之后再设置
System.out.println("===ftp login===");
//连接后检测返回码来校验连接是否成功
reply = ftp.getReplyCode();
System.out.println("===reply : "+reply+"===");
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("===ftp disconnect===");
}
boolean bool = ftp.changeWorkingDirectory(REMOTE_PATH);//转移到FTP服务器目录
System.out.println("===bool : "+bool+"===");
System.out.println("===ftp disrectory===");
ftp.enterLocalPassiveMode();
FTPFile[] fs = ftp.listFiles();
System.out.println("===ftp files===");
System.out.println("fs length : "+fs.length+"===");
for(FTPFile ff:fs){
String currentFileName = ff.getName();
if (currentFileName.startsWith(".")) {
System.out.println("===skipping file : "+currentFileName+"===");
continue;
}
System.out.println("===file name : "+currentFileName+"===");
File localFile = new File(lOCAL_PATH+"/"+currentFileName);
OutputStream is = new FileOutputStream(localFile);
boolean bool1 = ftp.retrieveFile(currentFileName, is);
System.err.println(bool1);
is.close();
}
ftp.logout();
System.out.println("===download end===");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
}
}