一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - 詳解JAVA中使用FTPClient工具類上傳下載

詳解JAVA中使用FTPClient工具類上傳下載

2020-12-09 14:04快樂的燕子會飛 Java教程

這篇文章主要介紹了JAVA中使用FTPClient工具類上傳下載的相關資料,java 使用FTP服務器上傳文件、下載文件,需要的朋友可以參考下

詳解JAVA中使用FTPClient工具類上傳下載

在Java程序中,經常需要和FTP打交道,比如向FTP服務器上傳文件、下載文件。本文簡單介紹如何利用jakarta commons中的FTPClient(在commons-net包中)實現上傳下載文件。

1、寫一個javabean文件,描述ftp上傳或下載的信息

實例代碼:

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
public class FtpUseBean {
  private String host;
  private Integer port;
  private String userName;
  private String password;
  private String ftpSeperator;
  private String ftpPath="";
  private int repeatTime = 0;//連接ftp服務器的次數
   
  public String getHost() {
    return host;
  }
   
  public void setHost(String host) {
    this.host = host;
  }
 
  public Integer getPort() {
    return port;
  }
  public void setPort(Integer port) {
    this.port = port;
  }
   
   
  public String getUserName() {
    return userName;
  }
   
  public void setUserName(String userName) {
    this.userName = userName;
  }
   
  public String getPassword() {
    return password;
  }
   
  public void setPassword(String password) {
    this.password = password;
  }
 
  public void setFtpSeperator(String ftpSeperator) {
    this.ftpSeperator = ftpSeperator;
  }
 
  public String getFtpSeperator() {
    return ftpSeperator;
  }
 
  public void setFtpPath(String ftpPath) {
    if(ftpPath!=null)
      this.ftpPath = ftpPath;
  }
 
  public String getFtpPath() {
    return ftpPath;
  }
 
  public void setRepeatTime(int repeatTime) {
    if (repeatTime > 0)
      this.repeatTime = repeatTime;
  }
 
  public int getRepeatTime() {
    return repeatTime;
  }
 
  /**
   * take an example:<br>
   * ftp://userName:password@ip:port/ftpPath/
   * @return
   */
  public String getFTPURL() {
    StringBuffer buf = new StringBuffer();
    buf.append("ftp://");
    buf.append(getUserName());
    buf.append(":");
    buf.append(getPassword());
    buf.append("@");
    buf.append(getHost());
    buf.append(":");
    buf.append(getPort());
    buf.append("/");
    buf.append(getFtpPath());
      
    return buf.toString();
  }
}

2、導入包commons-net-1.4.1.jar 

 
?
1
 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package com.util;
 
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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 com.bean.FtpUseBean;
 
public class FtpUtil extends FTPClient {
 
  private static Log log = LogFactory.getLog(FtpUtil.class);
  private FtpUseBean ftpUseBean;
  //獲取目標路徑下的文件屬性信息,主要是獲取文件的size
  private FTPFile[] files;
     
  public FtpUseBean getFtpUseBean() {
    return ftpUseBean;
  }
 
 
  public FtpUtil(){
    super();
  }
   
   
  public void setFtpUseBean(FtpUseBean ftpUseBean) {
    this.ftpUseBean = ftpUseBean;
  }
   
  public boolean ftpLogin() {
    boolean isLogined = false;
    try {
      log.debug("ftp login start ...");
      int repeatTime = ftpUseBean.getRepeatTime();
      for (int i = 0; i < repeatTime; i++) {
        super.connect(ftpUseBean.getHost(), ftpUseBean.getPort());
        isLogined = super.login(ftpUseBean.getUserName(), ftpUseBean.getPassword());
        if (isLogined)
          break;
      }
      if(isLogined)
        log.debug("ftp login successfully ...");
      else
        log.debug("ftp login failed ...");
      return isLogined;
    } catch (SocketException e) {
      log.error("", e);
      return false;
    } catch (IOException e) {
      log.error("", e);
      return false;
    } catch (RuntimeException e) {
      log.error("", e);
      return false;
    }
  }
 
  public void setFtpToUtf8() throws IOException {
 
    FTPClientConfig conf = new FTPClientConfig();
    super.configure(conf);
    super.setFileType(FTP.IMAGE_FILE_TYPE);
    int reply = super.sendCommand("OPTS UTF8 ON");
    if (reply == 200) { // UTF8 Command
      super.setControlEncoding("UTF-8");
    }
 
  }
 
  public void close() {
    if (super.isConnected()) {
      try {
        super.logout();
        super.disconnect();
        log.debug("ftp logout ....");
      } catch (Exception e) {
        log.error(e.getMessage());
        throw new RuntimeException(e.toString());
      }
    }
  }
 
  public void uploadFileToFtpByIS(InputStream inputStream, String fileName) throws IOException {
    super.storeFile(ftpUseBean.getFtpPath()+fileName, inputStream);
  }
 
  public File downFtpFile(String fileName, String localFileName) throws IOException {
    File outfile = new File(localFileName);
    OutputStream oStream = null;
    try {
      oStream = new FileOutputStream(outfile);
      super.retrieveFile(ftpUseBean.getFtpPath()+fileName, oStream);
      return outfile;
    } finally {
      if (oStream != null)
        oStream.close();
    }
  }
 
 
  public FTPFile[] listFtpFiles() throws IOException {
    return super.listFiles(ftpUseBean.getFtpPath());
  }
 
  public void deleteFtpFiles(FTPFile[] ftpFiles) throws IOException {
    String path = ftpUseBean.getFtpPath();
    for (FTPFile ff : ftpFiles) {
      if (ff.isFile()) {
        if (!super.deleteFile(path + ff.getName()))
          throw new RuntimeException("delete File" + ff.getName() + " is n't seccess");
      }
    }
  }
 
  public void deleteFtpFile(String fileName) throws IOException {
    if (!super.deleteFile(ftpUseBean.getFtpPath() +fileName))
      throw new RuntimeException("delete File" + ftpUseBean.getFtpPath() +fileName + " is n't seccess");
  }
 
  public InputStream downFtpFile(String fileName) throws IOException {
    return super.retrieveFileStream(ftpUseBean.getFtpPath()+fileName);
  }
 
  /**
   *
   * @return
   * @return StringBuffer
   * @description 下載ftp服務器上的文件,addr為帶用戶名和密碼的URL
   */
  public StringBuffer downloadBufferByURL(String addr) {
    BufferedReader in = null;
    try {
      URL url = new URL(addr);
      URLConnection conn = url.openConnection();
      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      StringBuffer ret = new StringBuffer();
      while ((line = in.readLine()) != null)
        ret.append(line);
       
      return ret;
    } catch (Exception e) {
      log.error(e);
      return null;
    } finally {
      try {
        if (null != in)
          in.close();
      } catch (IOException e) {
        e.printStackTrace();
        log.error(e);
      }
    }
  }
 
  /**
   *
   * @return
   * @return byte[]
   * @description 下載ftp服務器上的文件,addr為帶用戶名和密碼的URL
   */
  public byte[] downloadByteByURL(String addr) {
     
    FTPClient ftp = null;
     
    try {
       
      URL url = new URL(addr);
       
      int port = url.getPort()!=-1?url.getPort():21;
      log.info("HOST:"+url.getHost());
      log.info("Port:"+port);
      log.info("USERINFO:"+url.getUserInfo());
      log.info("PATH:"+url.getPath());
       
      ftp = new FTPClient();
       
      ftp.setDataTimeout(30000);
      ftp.setDefaultTimeout(30000);
      ftp.setReaderThread(false);
      ftp.connect(url.getHost(), port);
      ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]);
      FTPClientConfig conf = new FTPClientConfig("UNIX");  
           ftp.configure(conf); 
      log.info(ftp.getReplyString());
       
      ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode() 
      ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); 
 
      int reply = ftp.sendCommand("OPTS UTF8 ON");// try to
       
      log.debug("alter to utf-8 encoding - reply:" + reply);
      if (reply == 200) { // UTF8 Command
        ftp.setControlEncoding("UTF-8");
      }
      ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
 
      log.info(ftp.getReplyString());
       
      ByteArrayOutputStream out=new ByteArrayOutputStream();
           DataOutputStream o=new DataOutputStream(out);
           String remotePath = url.getPath();
           /**
           * Fixed:if doen't remove the first "/" at the head of url,
            * the file can't be retrieved.
           */
           if(remotePath.indexOf("/")==0) {
             remotePath = url.getPath().replaceFirst("/", "");
           }
           ftp.retrieveFile(remotePath, o);      
      byte[] ret = out.toByteArray();
      o.close();
       
      String filepath = url.getPath();
      ftp.changeWorkingDirectory(filepath.substring(0,filepath.lastIndexOf("/")));
      files = ftp.listFiles();
       
      return ret;
        } catch (Exception ex) {
      log.error("Failed to download file from ["+addr+"]!"+ex);
       } finally {
      try {
        if (null!=ftp)
          ftp.disconnect();
      } catch (Exception e) {
        //
      }
    }
    return null;
//   StringBuffer buffer = downloadBufferByURL(addr);
//   return null == buffer ? null : buffer.toString().getBytes();
  }
   
   
   
   
  public FTPFile[] getFiles() {
    return files;
  }
 
 
  public void setFiles(FTPFile[] files) {
    this.files = files;
  }
 
 
// public static void getftpfilesize(String addr){
//   
//   FTPClient ftp = null;
//   
//   try {
//     
//     URL url = new URL(addr);
//     
//     int port = url.getPort()!=-1?url.getPort():21;
//     log.info("HOST:"+url.getHost());
//     log.info("Port:"+port);
//     log.info("USERINFO:"+url.getUserInfo());
//     log.info("PATH:"+url.getPath());
//     
//     ftp = new FTPClient();
//     
//     ftp.setDataTimeout(30000);
//     ftp.setDefaultTimeout(30000);
//     ftp.setReaderThread(false);
//     ftp.connect(url.getHost(), port);
//     ftp.login(url.getUserInfo().split(":")[0], url.getUserInfo().split(":")[1]);
//     FTPClientConfig conf = new FTPClientConfig("UNIX");  
//     ftp.configure(conf); 
//     log.info(ftp.getReplyString());
//     
//     ftp.enterLocalPassiveMode(); //ftp.enterRemotePassiveMode() 
//     ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); 
//
//     int reply = ftp.sendCommand("OPTS UTF8 ON");// try to
//     
//     log.debug("alter to utf-8 encoding - reply:" + reply);
//     if (reply == 200) { // UTF8 Command
//       ftp.setControlEncoding("UTF-8");
//     }
//     ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
//     ftp.changeWorkingDirectory(url.getPath());
//     FTPFile[] files = ftp.listFiles();
//     for (FTPFile flie : files){
//       System.out.println(new String(flie.getName().getBytes("gbk"),"ISO8859-1"));
//       System.out.println(flie.getSize());
//     }
//     
//
//   } catch (Exception ex) {
//     log.error("Failed to download file from ["+addr+"]!"+ex);
//   } finally {
//     try {<pre class="java" name="code">     if (null!=ftp)
//     ftp.disconnect();
 //     } catch (Exception e) {
}
}
}
}

以上就是JAVA FTPClient工具類的上傳和下載的實例詳解,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

原文鏈接:http://blog.csdn.net/jzhf2012/article/details/8455044

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 轻轻操在线视频 | 青青草原国产视频 | 国产一区二区视频在线观看 | 国产成人精品免费大全 | 韩国丽卡三级作品 | 男人的天堂久久精品激情a 男人的天堂va | 性妲己 | 2022国产麻豆剧传媒古装 | 性的张力 | 亚洲欧美日韩另类在线 | 日本一区二区在线不卡 | 亚洲高清无在码在线电影 | 9久爱午夜视频 | 亚洲福利区 | 精品久久成人免费第三区 | 91大神第九部红酒气质女 | 午夜宅男网 | 日本高清视频在线观看 | 色老板视频在线 | 99久久精品国产免看国产一区 | 精品国产乱码久久久久久免费流畅 | 国产亚洲精品视频中文字幕 | 91国产在线播放 | 国产青草亚洲香蕉精品久久 | 欧美亚洲国产一区二区三区 | 爱操综合| chinese老头和老太交hd | 十六以下岁女子毛片免费 | 操弄哥哥的108种姿势 | 久久综合给会久久狠狠狠 | 久见久热 这里只有精品 | 国产成人精品免费久久久久 | 国产二区精品视频 | 国产网站免费在线观看 | 67id人成观看免费 | 国产成人福利美女观看视频 | 精品国产区一区二区三区在线观看 | 国产精品嫩草影院一二三区 | 国产重口老太伦 | 亚洲精品91大神在线观看 | 日韩成人在线影院 |