Java实现FTP文件与文件夹的上传和下载
Java实现FTP文件与文件夹的上传和下载
FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议”。用于Internet上的控制文件的双向传输。同时,它也是一个应用程序(Application)。基于不同的操作系统有不同的FTP应用程序,而所有这些应用程序都遵守同一种协议以传输文件。在FTP的使用当中,用户经常遇到两个概念:"下载"(Download)和"上传"(Upload)。"下载"文件就是从远程主机拷贝文件至自己的计算机上;"上传"文件就是将文件从自己的计算机中拷贝至远程主机上。用Internet语言来说,用户可通过客户机程序向(从)远程主机上传(下载)文件。
首先下载了Serv-U将自己的电脑设置为了FTP文件服务器,方便操作。下面代码的使用都是在FTP服务器已经创建,并且要在代码中写好FTP连接的相关数据才可以完成。
1.FTP文件的上传与下载(注意是单个文件的上传与下载)
- 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.FTP;
- import org.apache.commons.net.ftp.FTPClient;
- import org.apache.commons.net.ftp.FTPFile;
- import org.apache.commons.net.ftp.FTPReply;
- /**
- * 实现FTP文件上传和文件下载
- */
- public class FtpApche {
- private static FTPClient ftpClient = new FTPClient();
- private static String encoding = System.getProperty("file.encoding");
- /**
- * Description: 向FTP服务器上传文件
- *
- * @Version1.0
- * @param url
- * FTP服务器hostname
- * @param port
- * FTP服务器端口
- * @param username
- * FTP登录账号
- * @param password
- * FTP登录密码
- * @param path
- * FTP服务器保存目录,如果是根目录则为“/”
- * @param filename
- * 上传到FTP服务器上的文件名
- * @param input
- * 本地文件输入流
- * @return 成功返回true,否则返回false
- */
- public static boolean uploadFile(String url, int port, String username,
- String password, String path, String filename, InputStream input) {
- boolean result = false;
- try {
- int reply;
- // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
- ftpClient.connect(url);
- // ftp.connect(url, port);// 连接FTP服务器
- // 登录
- ftpClient.login(username, password);
- ftpClient.setControlEncoding(encoding);
- // 检验是否连接成功
- reply = ftpClient.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- System.out.println("连接失败");
- ftpClient.disconnect();
- return result;
- }
- // 转移工作目录至指定目录下
- boolean change = ftpClient.changeWorkingDirectory(path);
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- if (change) {
- result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"), input);
- if (result) {
- System.out.println("上传成功!");
- }
- }
- input.close();
- ftpClient.logout();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (ftpClient.isConnected()) {
- try {
- ftpClient.disconnect();
- } catch (IOException ioe) {
- }
- }
- }
- return result;
- }
- /**
- * 将本地文件上传到FTP服务器上
- *
- */
- public void testUpLoadFromDisk() {
- try {
- FileInputStream in = new FileInputStream(new File("D:/test02/list.txt"));
- boolean flag = uploadFile("10.0.0.102", 21, "admin","123456", "/", "lis.txt", in);
- System.out.println(flag);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- /**
- * Description: 从FTP服务器下载文件
- *
- * @Version1.0
- * @param url
- * FTP服务器hostname
- * @param port
- * FTP服务器端口
- * @param username
- * FTP登录账号
- * @param password
- * FTP登录密码
- * @param remotePath
- * FTP服务器上的相对路径
- * @param fileName
- * 要下载的文件名
- * @param localPath
- * 下载后保存到本地的路径
- * @return
- */
- public static boolean downFile(String url, int port, String username,
- String password, String remotePath, String fileName,
- String localPath) {
- boolean result = false;
- try {
- int reply;
- ftpClient.setControlEncoding(encoding);
- /*
- * 为了上传和下载中文文件,有些地方建议使用以下两句代替
- * new String(remotePath.getBytes(encoding),"iso-8859-1")转码。
- * 经过测试,通不过。
- */
- // FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
- // conf.setServerLanguageCode("zh");
- ftpClient.connect(url, port);
- // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
- ftpClient.login(username, password);// 登录
- // 设置文件传输类型为二进制
- ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
- // 获取ftp登录应答代码
- reply = ftpClient.getReplyCode();
- // 验证是否登陆成功
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftpClient.disconnect();
- System.err.println("FTP server refused connection.");
- return result;
- }
- // 转移到FTP服务器目录至指定的目录下
- ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
- // 获取文件列表
- FTPFile[] fs = ftpClient.listFiles();
- for (FTPFile ff : fs) {
- if (ff.getName().equals(fileName)) {
- File localFile = new File(localPath + "/" + ff.getName());
- OutputStream is = new FileOutputStream(localFile);
- ftpClient.retrieveFile(ff.getName(), is);
- is.close();
- }
- }
- ftpClient.logout();
- result = true;
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (ftpClient.isConnected()) {
- try {
- ftpClient.disconnect();
- } catch (IOException ioe) {
- }
- }
- }
- return result;
- }
- /**
- * 将FTP服务器上文件下载到本地
- *
- */
- public void testDownFile() {
- try {
- boolean flag = downFile("10.0.0.102", 21, "admin",
- "123456", "/", "ip.txt", "E:/");
- System.out.println(flag);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- FtpApche fa = new FtpApche();
- fa.testDownFile();
- fa.testUpLoadFromDisk();
- }
- }
2.FTP文件夹的上传与下载(注意是整个文件夹)
- package ftp;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.TimeZone;
- 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;
- import org.apache.log4j.Logger;
- public class FTPTest_04 {
- private FTPClient ftpClient;
- private String strIp;
- private int intPort;
- private String user;
- private String password;
- private static Logger logger = Logger.getLogger(FTPTest_04.class.getName());
- /* *
- * Ftp构造函数
- */
- public FTPTest_04(String strIp, int intPort, String user, String Password) {
- this.strIp = strIp;
- this.intPort = intPort;
- this.user = user;
- this.password = Password;
- this.ftpClient = new FTPClient();
- }
- /**
- * @return 判断是否登入成功
- * */
- public boolean ftpLogin() {
- boolean isLogin = false;
- FTPClientConfig ftpClientConfig = new FTPClientConfig();
- ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
- this.ftpClient.setControlEncoding("GBK");
- this.ftpClient.configure(ftpClientConfig);
- try {
- if (this.intPort > 0) {
- this.ftpClient.connect(this.strIp, this.intPort);
- }else {
- this.ftpClient.connect(this.strIp);
- }
- // FTP服务器连接回答
- int reply = this.ftpClient.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- this.ftpClient.disconnect();
- logger.error("登录FTP服务失败!");
- return isLogin;
- }
- this.ftpClient.login(this.user, this.password);
- // 设置传输协议
- this.ftpClient.enterLocalPassiveMode();
- this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
- logger.info("恭喜" + this.user + "成功登陆FTP服务器");
- isLogin = true;
- }catch (Exception e) {
- e.printStackTrace();
- logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
- }
- this.ftpClient.setBufferSize(1024 * 2);
- this.ftpClient.setDataTimeout(30 * 1000);
- return isLogin;
- }
- /**
- * @退出关闭服务器链接
- * */
- public void ftpLogOut() {
- if (null != this.ftpClient && this.ftpClient.isConnected()) {
- try {
- boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
- if (reuslt) {
- logger.info("成功退出服务器");
- }
- }catch (IOException e) {
- e.printStackTrace();
- logger.warn("退出FTP服务器异常!" + e.getMessage());
- }finally {
- try {
- this.ftpClient.disconnect();// 关闭FTP服务器的连接
- }catch (IOException e) {
- e.printStackTrace();
- logger.warn("关闭FTP服务器的连接异常!");
- }
- }
- }
- }
- /***
- * 上传Ftp文件
- * @param localFile 当地文件
- * @param romotUpLoadePath上传服务器路径 - 应该以/结束
- * */
- public boolean uploadFile(File localFile, String romotUpLoadePath) {
- BufferedInputStream inStream = null;
- boolean success = false;
- try {
- this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
- inStream = new BufferedInputStream(new FileInputStream(localFile));
- logger.info(localFile.getName() + "开始上传.....");
- success = this.ftpClient.storeFile(localFile.getName(), inStream);
- if (success == true) {
- logger.info(localFile.getName() + "上传成功");
- return success;
- }
- }catch (FileNotFoundException e) {
- e.printStackTrace();
- logger.error(localFile + "未找到");
- }catch (IOException e) {
- e.printStackTrace();
- }finally {
- if (inStream != null) {
- try {
- inStream.close();
- }catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return success;
- }
- /***
- * 下载文件
- * @param remoteFileName 待下载文件名称
- * @param localDires 下载到当地那个路径下
- * @param remoteDownLoadPath remoteFileName所在的路径
- * */
- public boolean downloadFile(String remoteFileName, String localDires,
- String remoteDownLoadPath) {
- String strFilePath = localDires + remoteFileName;
- BufferedOutputStream outStream = null;
- boolean success = false;
- try {
- this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
- outStream = new BufferedOutputStream(new FileOutputStream(
- strFilePath));
- logger.info(remoteFileName + "开始下载....");
- success = this.ftpClient.retrieveFile(remoteFileName, outStream);
- if (success == true) {
- logger.info(remoteFileName + "成功下载到" + strFilePath);
- return success;
- }
- }catch (Exception e) {
- e.printStackTrace();
- logger.error(remoteFileName + "下载失败");
- }finally {
- if (null != outStream) {
- try {
- outStream.flush();
- outStream.close();
- }catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- if (success == false) {
- logger.error(remoteFileName + "下载失败!!!");
- }
- return success;
- }
- /***
- * @上传文件夹
- * @param localDirectory
- * 当地文件夹
- * @param remoteDirectoryPath
- * Ftp 服务器路径 以目录"/"结束
- * */
- public boolean uploadDirectory(String localDirectory,
- String remoteDirectoryPath) {
- File src = new File(localDirectory);
- try {
- remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
- boolean makeDirFlag = this.ftpClient.makeDirectory(remoteDirectoryPath);
- System.out.println("localDirectory : " + localDirectory);
- System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
- System.out.println("src.getName() : " + src.getName());
- System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);
- System.out.println("makeDirFlag : " + makeDirFlag);
- // ftpClient.listDirectories();
- }catch (IOException e) {
- e.printStackTrace();
- logger.info(remoteDirectoryPath + "目录创建失败");
- }
- File[] allFile = src.listFiles();
- for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
- if (!allFile[currentFile].isDirectory()) {
- String srcName = allFile[currentFile].getPath().toString();
- uploadFile(new File(srcName), remoteDirectoryPath);
- }
- }
- for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
- if (allFile[currentFile].isDirectory()) {
- // 递归
- uploadDirectory(allFile[currentFile].getPath().toString(),
- remoteDirectoryPath);
- }
- }
- return true;
- }
- /***
- * @下载文件夹
- * @param localDirectoryPath本地地址
- * @param remoteDirectory 远程文件夹
- * */
- public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {
- try {
- String fileName = new File(remoteDirectory).getName();
- localDirectoryPath = localDirectoryPath + fileName + "//";
- new File(localDirectoryPath).mkdirs();
- FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
- for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
- if (!allFile[currentFile].isDirectory()) {
- downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory);
- }
- }
- for (int currentFile = 0;currentFile < allFile.length;currentFile++) {
- if (allFile[currentFile].isDirectory()) {
- String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();
- downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);
- }
- }
- }catch (IOException e) {
- e.printStackTrace();
- logger.info("下载文件夹失败");
- return false;
- }
- return true;
- }
- // FtpClient的Set 和 Get 函数
- public FTPClient getFtpClient() {
- return ftpClient;
- }
- public void setFtpClient(FTPClient ftpClient) {
- this.ftpClient = ftpClient;
- }
- public static void main(String[] args) throws IOException {
- FTPTest_04 ftp=new FTPTest_04("10.0.0.102",21,"admin","123456");
- ftp.ftpLogin();
- System.out.println("1");
- //上传文件夹
- boolean uploadFlag = ftp.uploadDirectory("D:\\test02", "/"); //如果是admin/那么传的就是所有文件,如果只是/那么就是传文件夹
- System.out.println("uploadFlag : " + uploadFlag);
- //下载文件夹
- ftp.downLoadDirectory("d:\\tm", "/");
- ftp.ftpLogOut();
- }
- }
Java实现FTP文件与文件夹的上传和下载的更多相关文章
- win7下利用ftp实现华为路由器的配置文件上传和下载
win7下利用ftp实现华为路由器的配置文件上传和下载 1. Win7下ftp的安装和配置 (1)开始—>控制面板—>程序—>程序和功能—>打开或关闭Windows功能 (2 ...
- 利用Apache commons-net 包进行FTP文件和文件夹的上传与下载
首先声明:这段代码是我在网上胡乱找的,调试后可用. 需要提前导入jar包,我导入的是:commons-net-3.0.1,在网上可以下载到.以下为源码,其中文件夹的下载存在问题:FTPFile[] a ...
- Java web开发——文件夹的上传和下载
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...
- JavaScript开发——文件夹的上传和下载
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...
- JS开发——文件夹的上传和下载
文件夹上传:从前端到后端 文件上传是 Web 开发肯定会碰到的问题,而文件夹上传则更加难缠.网上关于文件夹上传的资料多集中在前端,缺少对于后端的关注,然后讲某个后端框架文件上传的文章又不会涉及文件夹. ...
- php web开发——文件夹的上传和下载
核心原理: 该项目核心就是文件分块上传.前后端要高度配合,需要双方约定好一些数据,才能完成大文件分块,我们在项目中要重点解决的以下问题. * 如何分片: * 如何合成一个文件: * 中断了从哪个分片开 ...
- 基于SMB共享文件夹的上传于下载
需要用到的jar包 http://pan.baidu.com/s/1skQFk77 1.首先在一台电脑上设置共享文件夹 ----上传下载的方法类 package com.strongit.tool ...
- 基于commons-net实现ftp创建文件夹、上传、下载功能
原文:http://www.open-open.com/code/view/1420774470187 package com.demo.ftp; import java.io.FileInputSt ...
- B/S开发——文件夹的上传和下载
本人在2010年时使用swfupload为核心进行文件的批量上传的解决方案.见文章:WEB版一次选择多个文件进行批量上传(swfupload)的解决方案. 本人在2013年时使用plupload为核心 ...
随机推荐
- 12306官方火车票Api接口
2017,现在已进入春运期间,真的是一票难求,深有体会.各种购票抢票软件应运而生,也有购买加速包提高抢票几率,可以理解为变相的黄牛.对于技术人员,虽然写一个抢票软件还是比较难的,但是还是简单看看123 ...
- node中的cmd规范
你应该熟悉nodejs模块中的exports对象,你可以用它创建你的模块.例如:(假设这是rocker.js文件) exports.name = function() { console.log('M ...
- Django admin定制化,User字段扩展[原创]
前言 参考上篇博文,我们利用了OneToOneField的方式使用了django自带的user,http://www.cnblogs.com/caseast/p/5909248.html , 但这么用 ...
- thinkphp数据的查询和截取
public function NewsList(){ $this->assign('title','news'); $p = I('page',1); $listRows = 6; $News ...
- Mysql基础代码(不断完善中)
Mysql基础代码,不断完善中~ /* 启动MySQL */ net start mysql /* 连接与断开服务器 */ mysql -h 地址 -P 端口 -u 用户名 -p 密码 /* 跳过权限 ...
- PHP设计模式(七)适配器模式(Adapter For PHP)
适配器模式:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作. 如下图(借图): // 设置书的接口 // 书接口 interface BookI ...
- 关于MJRefresh的下拉加载数据bug
当没有更多数据的时候显示NoMoreData 我的理解是先结束刷新再显示没有更多 今天之前一直没发现有问题 贴之前的代码 [self.collectionView reloadData]; [self ...
- SQL-日期函数
GETDATE() :取得当前日期时间 DATEADD (datepart , number, date ),计算增加以后的日期.参数date为待计算的日期:参数number为增量:参数datepar ...
- (转)从0开始搭建SQL Server AlwaysOn 第二篇(配置故障转移集群)
原文地址: http://www.cnblogs.com/lyhabc/p/4682028.html 这一篇是从0开始搭建SQL Server AlwaysOn 的第二篇,主要讲述如何搭建故障转移集 ...
- TFS 生成配置
生成