首页 > 代码库 > FTP工具类
FTP工具类
包含上传文件,和下载文件,需要两个jar包一个common-net.jar 和 jakarta-oro-2.0.8.jar
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUtil2 {
public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);//连接FTP服务器
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
public static void main(String[] args) {
/*FileInputStream in=new FileInputStream(new File("D:/test.txt")); */
boolean flag = downFile("172.16.6.89", 21, "dzj", "123456", "333", "test1.txt", "D:/test");
System.out.println(flag);
}
public static boolean downFile(String url, int port,String username, String password, String remotePath,String fileName,String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
//链接路径与端口
ftp.connect(url, port);
//设置编码格式,否则文件名称为乱码
ftp.setControlEncoding("gbk");
/* FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");*/
//登录账号密码
ftp.login(username, password);//登录
/* ftp.setFileType(FTPClient.BINARY_FILE_TYPE); */
//返回状态码
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
//断开连接
ftp.disconnect();
return success;
}
//修改ftp上传的目录,必须ftp存在这个目录
ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
//这个地方需要jakarta-oro-2.0.8.jar ,否则无法转换成file
FTPFile[] fs = ftp.listFiles();
for(FTPFile ff:fs){
File localFile = new File(localPath+"/"+ff.getName());
FileUtil.createParentFile(localFile);
FileOutputStream is = new FileOutputStream(localFile);
//这里的编码转换必须有,否则生成的文本文件就是空的
// ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), is);
// URLEncoder 防止下载时候出现中文乱码
//response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
ftp.deleteFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"));
is.close();
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
}
FTP工具类