您的位置:首页 > 编程语言 > Java开发

java实现ftp文件的上传与下载

2017-10-18 16:56 836 查看
转自:http://www.cnblogs.com/huzi007/p/4236150.html

最近在做ftp文件的上传与下载,基于此,整理了一下资料。本来想采用java自带的方法,可是看了一下jdk1.6与1.7的实现方法有点区别,于是采用了Apache下的框架实现的。。。

1.首先引用3个包



 

2.然后是相关类的代码



1 /**
2  * ftp链接常量
3  *
4  */
5 public class Ftp {
6
7     private String ipAddr;//ip地址
8
9     private Integer port;//端口号
10
11     private String userName;//用户名
12
13     private String pwd;//密码
14
15     private String path;//aaa路径
16
17     public String getIpAddr() {
18         return ipAddr;
19     }
20
21     public void setIpAddr(String ipAddr) {
22         this.ipAddr = ipAddr;
23     }
24
25     public Integer getPort() {
26         return port;
27     }
28
29     public void setPort(Integer port) {
30         this.port = port;
31     }
32
33     public String getUserName() {
34         return userName;
35     }
36
37     public void setUserName(String userName) {
38         this.userName = userName;
39     }
40
41     public String getPwd() {
42         return pwd;
43     }
44
45     public void setPwd(String pwd) {
46         this.pwd = pwd;
47     }
48
49     public String getPath() {
50         return path;
51     }
52
53     public void setPath(String path) {
54         this.path = path;
55     }
56
57
58 }




 



1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.FileOutputStream;
4 import java.io.IOException;
5 import java.io.OutputStream;
6
7
8 import org.apache.commons.net.ftp.FTPClient;
9 import org.apache.commons.net.ftp.FTPFile;
10 import org.apache.commons.net.ftp.FTPReply;
11 import org.apache.log4j.Logger;
12
13 public class FtpUtil {
14
15     private static Logger logger=Logger.getLogger(FtpUtil.class);
16
17     private static FTPClient ftp;
18
19     /**
20      * 获取ftp连接
21      * @param f
22      * @return
23      * @throws Exception
24      */
25     public static boolean connectFtp(Ftp f) throws Exception{
26         ftp=new FTPClient();
27         boolean flag=false;
28         int reply;
29         if (f.getPort()==null) {
30             ftp.connect(f.getIpAddr(),21);
31         }else{
32             ftp.connect(f.getIpAddr(),f.getPort());
33         }
34         ftp.login(f.getUserName(), f.getPwd());
35         ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
36         reply = ftp.getReplyCode();
37         if (!FTPReply.isPositiveCompletion(reply)) {
38               ftp.disconnect();
39               return flag;
40         }
41         ftp.changeWorkingDirectory(f.getPath());
42         flag = true;
43         return flag;
44     }
45
46     /**
47      * 关闭ftp连接
48      */
49     public static void closeFtp(){
50         if (ftp!=null && ftp.isConnected()) {
51             try {
52                 ftp.logout();
53                 ftp.disconnect();
54             } catch (IOException e) {
55                 e.printStackTrace();
56             }
57         }
58     }
59
60     /**
61      * ftp上传文件
62      * @param f
63      * @throws Exception
64      */
65     public static void upload(File f) throws Exception{
66         if (f.isDirectory()) {
67             ftp.makeDirectory(f.getName());
68             ftp.changeWorkingDirectory(f.getName());
69             String[] files=f.list();
70             for(String fstr : files){
71                 File file1=new File(f.getPath()+"/"+fstr);
72                 if (file1.isDirectory()) {
73                     upload(file1);
74                     ftp.changeToParentDirectory();
75                 }else{
76                     File file2=new File(f.getPath()+"/"+fstr);
77                     FileInputStream input=new FileInputStream(file2);
78                     ftp.storeFile(file2.getName(),input);
79                     input.close();
80                 }
81             }
82         }else{
83             File file2=new File(f.getPath());
84             FileInputStream input=new FileInputStream(file2);
85             ftp.storeFile(file2.getName(),input);
86             input.close();
87         }
88     }
89
90     /**
91      * 下载链接配置
92      * @param f
93      * @param localBaseDir 本地目录
94      * @param remoteBaseDir 远程目录
95      * @throws Exception
96      */
97     public static void startDown(Ftp f,String localBaseDir,String remoteBaseDir ) throws Exception{
98         if (FtpUtil.connectFtp(f)) {
99
100             try {
101                 FTPFile[] files = null;
102                 boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir);
103                 if (changedir) {
104                     ftp.setControlEncoding("GBK");
105                     files = ftp.listFiles();
106                     for (int i = 0; i < files.length; i++) {
107                         try{
108                             downloadFile(files[i], localBaseDir, remoteBaseDir);
109                         }catch(Exception e){
110                             logger.error(e);
111                             logger.error("<"+files[i].getName()+">下载失败");
112                         }
113                     }
114                 }
115             } catch (Exception e) {
116                 logger.error(e);
117                 logger.error("下载过程中出现异常");
118             }
119         }else{
120             logger.error("链接失败!");
121         }
122
123     }
124
125
126     /**
127      *
128      * 下载FTP文件
129      * 当你需要下载FTP文件的时候,调用此方法
130      * 根据<b>获取的文件名,本地地址,远程地址</b>进行下载
131      *
132      * @param ftpFile
133      * @param relativeLocalPath
134      * @param relativeRemotePath
135      */
136     private  static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) {
137         if (ftpFile.isFile()) {
138             if (ftpFile.getName().indexOf("?") == -1) {
139                 OutputStream outputStream = null;
140                 try {
141                     File locaFile= new File(relativeLocalPath+ ftpFile.getName());
142                     //判断文件是否存在,存在则返回
143                     if(locaFile.exists()){
144                         return;
145                     }else{
146                         outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName());
147                         ftp.retrieveFile(ftpFile.getName(), outputStream);
148                         outputStream.flush();
149                         outputStream.close();
150                     }
151                 } catch (Exception e) {
152                     logger.error(e);
153                 } finally {
154                     try {
155                         if (outputStream != null){
156                             outputStream.close();
157                         }
158                     } catch (IOException e) {
159                        logger.error("输出文件流异常");
160                     }
161                 }
162             }
163         } else {
164             String newlocalRelatePath = relativeLocalPath + ftpFile.getName();
165             String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString());
166             File fl = new File(newlocalRelatePath);
167             if (!fl.exists()) {
168                 fl.mkdirs();
169             }
170             try {
171                 newlocalRelatePath = newlocalRelatePath + '/';
172                 newRemote = newRemote + "/";
173                 String currentWorkDir = ftpFile.getName().toString();
174                 boolean changedir = ftp.changeWorkingDirectory(currentWorkDir);
175                 if (changedir) {
176                     FTPFile[] files = null;
177                     files = ftp.listFiles();
178                     for (int i = 0; i < files.length; i++) {
179                         downloadFile(files[i], newlocalRelatePath, newRemote);
180                     }
181                 }
182                 if (changedir){
183                     ftp.changeToParentDirectory();
184                 }
185             } catch (Exception e) {
186                 logger.error(e);
187             }
188         }
189     }
190
191
192     public static void main(String[] args) throws Exception{
193             Ftp f=new Ftp();
194             f.setIpAddr("1111");
195             f.setUserName("root");
196             f.setPwd("111111");
197             FtpUtil.connectFtp(f);
198             File file = new File("F:/test/com/test/Testng.java");
199             FtpUtil.upload(file);//把文件上传在ftp上
200             FtpUtil.startDown(f, "e:/",  "/xxtest");//下载ftp文件测试
201             System.out.println("ok");
202
203        }
204
205 }




以上代码均测试通过了。。。

package com.ftp;
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class Test {

private FTPClient ftp;
/**
*
* @param path 上传到ftp服务器哪个路径下
* @param addr 地址
* @param port 端口号
* @param username 用户名
* @param password 密码
* @return
* @throws Exception
*/
private boolean connect(String path,String addr,int port,String username,String password) throws Exception {
boolean result = false;
ftp = new FTPClient();
int reply;
ftp.connect(addr,port);
ftp.login(username,password);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(path);
result = true;
return result;
}
/**
*
* @param file 上传的文件或文件夹
* @throws Exception
*/
private void upload(File file) throws Exception{
if(file.isDirectory()){
ftp.makeDirectory(file.getName());
ftp.changeWorkingDirectory(file.getName());
String[] files = file.list();
for (int i = 0; i < files.length; i++) {
File file1 = new File(file.getPath()+"\\"+files[i] );
if(file1.isDirectory()){
upload(file1);
ftp.changeToParentDirectory();
}else{
File file2 = new File(file.getPath()+"\\"+files[i]);
FileInputStream input = new FileInputStream(file2);
ftp.storeFile(file2.getName(), input);
input.close();
}
}
}else{
File file2 = new File(file.getPath());
FileInputStream input = new FileInputStream(file2);
ftp.storeFile(file2.getName(), input);
input.close();
}
}
public static void main(String[] args) throws Exception{
Test t = new Test();
t.connect("/xxtest", "115.28.147.188", 21, "root", "cqmyg123");
File file = new File("F:/java.zip");
t.upload(file);
System.out.println("ok");

}
}

项目及相关包下载:http://pan.baidu.com/s/1hq5p7NI
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: