设为首页 收藏本站
查看: 1271|回复: 0

[经验分享] java FTP 上传 下载 (中文 ) 文件

[复制链接]

尚未签到

发表于 2016-6-9 09:56:41 | 显示全部楼层 |阅读模式
最近需要做一个 上传zip文件到ftp服务器的功能。在网上找了一些资料终于成功了,包括
上传  下载  和 列出所有文件。 以及各种中文乱码的解决:以下是代码:具体的文件和所需jar包在附件中

package com.galen;
import java.io.BufferedInputStream;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTP;
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 FTPHandle {
private String username;
private String password;
private String ip;
private int port;
private static Properties property = null;// 配置
private String configFile;// 配置文件的路径名
private FTPClient ftpClient = null;
private String filedir = "";// FTP文件路径
private final String[] FILE_TYPES = { "文件", "目录", "符号链接", "未知类型" };
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
/**
* 设置参数
* @param configFile  --参数的配置文件
*/
private void setArg(String configFile) {
property = new Properties();
BufferedInputStream inBuff = null;
try {
inBuff = new BufferedInputStream(new FileInputStream(new File(
System.getProperty("user.dir") + configFile)));
property.load(inBuff);
username = property.getProperty("username");
password = property.getProperty("password");
ip = property.getProperty("ip");
port = Integer.parseInt(property.getProperty("port"));
filedir = property.getProperty("filedir");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inBuff != null)
inBuff.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 设置FTP客服端的配置--一般可以不设置
* @return
*/
private FTPClientConfig getFtpConfig() {
FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
return ftpConfig;
}
/**
* 连接到服务器
*/
public void connectServer() {
if (ftpClient == null) {
int reply;
try {
setArg(configFile);
ftpClient = new FTPClient();
ftpClient.configure(getFtpConfig());
ftpClient.connect(ip);
ftpClient.login(username, password);
ftpClient.setDefaultPort(port);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//此设置可以用来上传BINARY二进制文件 比如 XXX.zip
System.out.print(ftpClient.getReplyString());
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
}
} catch (Exception e) {
System.err.println("登录ftp服务器【" + ip + "】失败");
e.printStackTrace();
}
}
}
/**
* 进入到服务器的某个目录下
* @param directory
*/
public void changeWorkingDirectory() {
try {
ftpClient.changeWorkingDirectory(filedir);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 上传文件
*
* @param inputStream
*            --文件输入流
* @param newFileName
*            --新的文件名
*/
public void uploadFile(InputStream inputStream, String newFileName) {
changeWorkingDirectory();// 进入文件夹
// 上传文件
BufferedInputStream buffIn = null;
try {
buffIn = new BufferedInputStream(inputStream);
ftpClient.storeFile(newFileName, buffIn);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (buffIn != null)
buffIn.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream(new File(
"d:\\temp\\CESQL071454545.txt"));
FTPHandle fh = new FTPHandle();
fh.setConfigFile("/ftpupload.properties");
fh.connectServer();
/* 上传文件 */
//fh.uploadFile(is, new String("CESQL071454545.txt".getBytes("GBK"),"iso-8859-1"));
/* 删除文件 */
// fh.deleteFile("CESQL071454545.txt");
/* 遍历文件 */
List<Map> files = fh.listRemoteFiles("/bo");
for (int i = 0; i < files.size(); i++) {
Map file = files.get(i);
System.out.print(file.get("filename"));
System.out.print("\t\t" + file.get("filesize") + "\t\t");
System.out.println(file.get("scsj"));
}
/* 下载文件 */
fh.loadFile(new String("测试.zip".getBytes("GBK"), "ISO-8859-1"),
"d:\\temp\\测试.zip");
fh.closeConnect();
}
/**
* 列出服务器上文件和目录
*
* @param regStr
*            --匹配的正则表达式
*/
@SuppressWarnings("unchecked")
public List listRemoteFiles(String regStr) {
List list = new ArrayList();
try {
ftpClient.setControlEncoding("GBK");
FTPFile[] files = ftpClient.listFiles(regStr);
if (files == null || files.length == 0) {
System.out.println("There has not any file!");
return null;
} else {
for (FTPFile file : files) {
if (file != null) {
Map map = new HashMap();
String filename = new String(file.getName().getBytes(
"GBK"), "iso-8859-1");
int filenamelen = filename.length();
if (filenamelen > 4) {
String filetype = filename
.substring(filenamelen - 3);
if (true) {
String name = file.getName();
// name = name.substring(0,name.length()-4);
map.put("filename", name);
map.put("filesize", FileUtils
.byteCountToDisplaySize(file.getSize()));
map.put("scsj", dateFormat.format(file
.getTimestamp().getTime()));
list.add(map);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 下载文件
*
* @param remoteFileName
*            --服务器上的文件名
* @param localFileName
*            --本地文件名
*/
public void loadFile(String remoteFileName, String localFileName) {
// 下载文件
BufferedOutputStream buffOut = null;
try {
buffOut = new BufferedOutputStream(new FileOutputStream(
localFileName));
ftpClient.setControlEncoding("GBK");
ftpClient.retrieveFile(remoteFileName, buffOut);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (buffOut != null)
buffOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 删除文件
*/
public void deleteFile(String filename) {
try {
ftpClient.deleteFile(filename);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 关闭连接
*/
public void closeConnect() {
try {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
System.out.println("Ftp have closed");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getConfigFile() {
return configFile;
}
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
public String[] getFILE_TYPES() {
return FILE_TYPES;
}
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public Properties getProperty() {
return property;
}
public void setProperty(Properties property) {
this.property = property;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFiledir() {
return filedir;
}
public void setFiledir(String filedir) {
this.filedir = filedir;
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-228112-1-1.html 上篇帖子: Oracle 10g asm ftp传输数据文件 下篇帖子: ftp简介、工作原理及常用命令<2>
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表