实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式,),分别为:1、通过JDK自带的API实现;2、通过Apache提供的API是实现。

第一种方式

[java] view plain copy
  1. package com.cloudpower.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import sun.net.TelnetInputStream;
  7. import sun.net.TelnetOutputStream;
  8. import sun.net.ftp.FtpClient;
  9. /**
  10. * Java自带的API对FTP的操作
  11. * @Title:Ftp.java
  12. * @author: 周玲斌
  13. */
  14. public class Ftp {
  15. /**
  16. * 本地文件名
  17. */
  18. private String localfilename;
  19. /**
  20. * 远程文件名
  21. */
  22. private String remotefilename;
  23. /**
  24. * FTP客户端
  25. */
  26. private FtpClient ftpClient;
  27. /**
  28. * 服务器连接
  29. * @param ip 服务器IP
  30. * @param port 服务器端口
  31. * @param user 用户名
  32. * @param password 密码
  33. * @param path 服务器路径
  34. * @author 周玲斌
  35. * @date   2012-7-11
  36. */
  37. public void connectServer(String ip, int port, String user,
  38. String password, String path) {
  39. try {
  40. /* ******连接服务器的两种方法*******/
  41. //第一种方法
  42. //            ftpClient = new FtpClient();
  43. //            ftpClient.openServer(ip, port);
  44. //第二种方法
  45. ftpClient = new FtpClient(ip);
  46. ftpClient.login(user, password);
  47. // 设置成2进制传输
  48. ftpClient.binary();
  49. System.out.println("login success!");
  50. if (path.length() != 0){
  51. //把远程系统上的目录切换到参数path所指定的目录
  52. ftpClient.cd(path);
  53. }
  54. ftpClient.binary();
  55. } catch (IOException ex) {
  56. ex.printStackTrace();
  57. throw new RuntimeException(ex);
  58. }
  59. }
  60. /**
  61. * 关闭连接
  62. * @author 周玲斌
  63. * @date   2012-7-11
  64. */
  65. public void closeConnect() {
  66. try {
  67. ftpClient.closeServer();
  68. System.out.println("disconnect success");
  69. } catch (IOException ex) {
  70. System.out.println("not disconnect");
  71. ex.printStackTrace();
  72. throw new RuntimeException(ex);
  73. }
  74. }
  75. /**
  76. * 上传文件
  77. * @param localFile 本地文件
  78. * @param remoteFile 远程文件
  79. * @author 周玲斌
  80. * @date   2012-7-11
  81. */
  82. public void upload(String localFile, String remoteFile) {
  83. this.localfilename = localFile;
  84. this.remotefilename = remoteFile;
  85. TelnetOutputStream os = null;
  86. FileInputStream is = null;
  87. try {
  88. //将远程文件加入输出流中
  89. os = ftpClient.put(this.remotefilename);
  90. //获取本地文件的输入流
  91. File file_in = new File(this.localfilename);
  92. is = new FileInputStream(file_in);
  93. //创建一个缓冲区
  94. byte[] bytes = new byte[1024];
  95. int c;
  96. while ((c = is.read(bytes)) != -1) {
  97. os.write(bytes, 0, c);
  98. }
  99. System.out.println("upload success");
  100. } catch (IOException ex) {
  101. System.out.println("not upload");
  102. ex.printStackTrace();
  103. throw new RuntimeException(ex);
  104. } finally{
  105. try {
  106. if(is != null){
  107. is.close();
  108. }
  109. } catch (IOException e) {
  110. e.printStackTrace();
  111. } finally {
  112. try {
  113. if(os != null){
  114. os.close();
  115. }
  116. } catch (IOException e) {
  117. e.printStackTrace();
  118. }
  119. }
  120. }
  121. }
  122. /**
  123. * 下载文件
  124. * @param remoteFile 远程文件路径(服务器端)
  125. * @param localFile 本地文件路径(客户端)
  126. * @author 周玲斌
  127. * @date   2012-7-11
  128. */
  129. public void download(String remoteFile, String localFile) {
  130. TelnetInputStream is = null;
  131. FileOutputStream os = null;
  132. try {
  133. //获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
  134. is = ftpClient.get(remoteFile);
  135. File file_in = new File(localFile);
  136. os = new FileOutputStream(file_in);
  137. byte[] bytes = new byte[1024];
  138. int c;
  139. while ((c = is.read(bytes)) != -1) {
  140. os.write(bytes, 0, c);
  141. }
  142. System.out.println("download success");
  143. } catch (IOException ex) {
  144. System.out.println("not download");
  145. ex.printStackTrace();
  146. throw new RuntimeException(ex);
  147. } finally{
  148. try {
  149. if(is != null){
  150. is.close();
  151. }
  152. } catch (IOException e) {
  153. e.printStackTrace();
  154. } finally {
  155. try {
  156. if(os != null){
  157. os.close();
  158. }
  159. } catch (IOException e) {
  160. e.printStackTrace();
  161. }
  162. }
  163. }
  164. }
  165. public static void main(String agrs[]) {
  166. String filepath[] = { "/temp/aa.txt", "/temp/regist.log"};
  167. String localfilepath[] = { "C:\\tmp\\1.txt","C:\\tmp\\2.log"};
  168. Ftp fu = new Ftp();
  169. /*
  170. * 使用默认的端口号、用户名、密码以及根目录连接FTP服务器
  171. */
  172. fu.connectServer("127.0.0.1", 22, "anonymous", "IEUser@", "/temp");
  173. //下载
  174. for (int i = 0; i < filepath.length; i++) {
  175. fu.download(filepath[i], localfilepath[i]);
  176. }
  177. String localfile = "E:\\号码.txt";
  178. String remotefile = "/temp/哈哈.txt";
  179. //上传
  180. fu.upload(localfile, remotefile);
  181. fu.closeConnect();
  182. }
  183. }

这种方式没啥可说的,比较简单,也不存在中文乱码的问题。貌似有个缺陷,不能操作大文件,有兴趣的朋友可以试试。

第二种方式

[java] view plain copy
  1. public class FtpApche {
  2. private static FTPClient ftpClient = new FTPClient();
  3. private static String encoding = System.getProperty("file.encoding");
  4. /**
  5. * Description: 向FTP服务器上传文件
  6. *
  7. * @Version1.0
  8. * @param url
  9. *            FTP服务器hostname
  10. * @param port
  11. *            FTP服务器端口
  12. * @param username
  13. *            FTP登录账号
  14. * @param password
  15. *            FTP登录密码
  16. * @param path
  17. *            FTP服务器保存目录,如果是根目录则为“/”
  18. * @param filename
  19. *            上传到FTP服务器上的文件名
  20. * @param input
  21. *            本地文件输入流
  22. * @return 成功返回true,否则返回false
  23. */
  24. public static boolean uploadFile(String url, int port, String username,
  25. String password, String path, String filename, InputStream input) {
  26. boolean result = false;
  27. try {
  28. int reply;
  29. // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
  30. ftpClient.connect(url);
  31. // ftp.connect(url, port);// 连接FTP服务器
  32. // 登录
  33. ftpClient.login(username, password);
  34. ftpClient.setControlEncoding(encoding);
  35. // 检验是否连接成功
  36. reply = ftpClient.getReplyCode();
  37. if (!FTPReply.isPositiveCompletion(reply)) {
  38. System.out.println("连接失败");
  39. ftpClient.disconnect();
  40. return result;
  41. }
  42. // 转移工作目录至指定目录下
  43. boolean change = ftpClient.changeWorkingDirectory(path);
  44. ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  45. if (change) {
  46. result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"), input);
  47. if (result) {
  48. System.out.println("上传成功!");
  49. }
  50. }
  51. input.close();
  52. ftpClient.logout();
  53. } catch (IOException e) {
  54. e.printStackTrace();
  55. } finally {
  56. if (ftpClient.isConnected()) {
  57. try {
  58. ftpClient.disconnect();
  59. } catch (IOException ioe) {
  60. }
  61. }
  62. }
  63. return result;
  64. }
  65. /**
  66. * 将本地文件上传到FTP服务器上
  67. *
  68. */
  69. public void testUpLoadFromDisk() {
  70. try {
  71. FileInputStream in = new FileInputStream(new File("E:/号码.txt"));
  72. boolean flag = uploadFile("127.0.0.1", 21, "zlb","123", "/", "哈哈.txt", in);
  73. System.out.println(flag);
  74. } catch (FileNotFoundException e) {
  75. e.printStackTrace();
  76. }
  77. }
  78. /**
  79. * Description: 从FTP服务器下载文件
  80. *
  81. * @Version1.0
  82. * @param url
  83. *            FTP服务器hostname
  84. * @param port
  85. *            FTP服务器端口
  86. * @param username
  87. *            FTP登录账号
  88. * @param password
  89. *            FTP登录密码
  90. * @param remotePath
  91. *            FTP服务器上的相对路径
  92. * @param fileName
  93. *            要下载的文件名
  94. * @param localPath
  95. *            下载后保存到本地的路径
  96. * @return
  97. */
  98. public static boolean downFile(String url, int port, String username,
  99. String password, String remotePath, String fileName,
  100. String localPath) {
  101. boolean result = false;
  102. try {
  103. int reply;
  104. ftpClient.setControlEncoding(encoding);
  105. /*
  106. *  为了上传和下载中文文件,有些地方建议使用以下两句代替
  107. *  new String(remotePath.getBytes(encoding),"iso-8859-1")转码。
  108. *  经过测试,通不过。
  109. */
  110. //            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
  111. //            conf.setServerLanguageCode("zh");
  112. ftpClient.connect(url, port);
  113. // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
  114. ftpClient.login(username, password);// 登录
  115. // 设置文件传输类型为二进制
  116. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  117. // 获取ftp登录应答代码
  118. reply = ftpClient.getReplyCode();
  119. // 验证是否登陆成功
  120. if (!FTPReply.isPositiveCompletion(reply)) {
  121. ftpClient.disconnect();
  122. System.err.println("FTP server refused connection.");
  123. return result;
  124. }
  125. // 转移到FTP服务器目录至指定的目录下
  126. ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
  127. // 获取文件列表
  128. FTPFile[] fs = ftpClient.listFiles();
  129. for (FTPFile ff : fs) {
  130. if (ff.getName().equals(fileName)) {
  131. File localFile = new File(localPath + "/" + ff.getName());
  132. OutputStream is = new FileOutputStream(localFile);
  133. ftpClient.retrieveFile(ff.getName(), is);
  134. is.close();
  135. }
  136. }
  137. ftpClient.logout();
  138. result = true;
  139. } catch (IOException e) {
  140. e.printStackTrace();
  141. } finally {
  142. if (ftpClient.isConnected()) {
  143. try {
  144. ftpClient.disconnect();
  145. } catch (IOException ioe) {
  146. }
  147. }
  148. }
  149. return result;
  150. }
  151. /**
  152. * 将FTP服务器上文件下载到本地
  153. *
  154. */
  155. public void testDownFile() {
  156. try {
  157. boolean flag = downFile("127.0.0.1", 21, "zlb",
  158. "123", "/", "哈哈.txt", "D:/");
  159. System.out.println(flag);
  160. } catch (Exception e) {
  161. e.printStackTrace();
  162. }
  163. }
  164. public static void main(String[] args) {
  165. FtpApche fa = new FtpApche();
  166. fa.testDownFile();
  167. }
  168. }

这种方式的话需要注意中文乱码问题啦,如果你设置不恰当,有可能上传的文件名会为乱码,有的时候根本就上传不上去,当然,也不会跟你提示,因为原本就没异常。在网上找了好多解答方案,众说纷纭,几乎都是从一个版本拷贝过去的,也没有经过自己的真是检验。为此,也吃了不少苦头。大致分为以下两种解决方案:

1、加上以下三句即可解决

ftpClient.setControlEncoding(“GBK”);

FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
解答:经过测试,根本上行不通,上述问题依然存在

2、与上述方式有所类似,但我觉得这种方式更靠谱一点

首先,加上ftpClient.setControlEncoding(“GBK”);这一句,然后,将所有的中文进行转码为“ISO-8859-1”格式,如下:

ftpClient.changeWorkingDirectory(new String(remotePath.getBytes("GBK"),"iso-8859-1"));

解答:经过测试,仍然行不通,之所以我说此方式更靠谱一点,请继续往下看

首先我们来说说为什么要进行转码:

因为在FTP协议里面,规定文件名编码为iso-8859-1,所以目录名或文件名需要转码。

接下来的问题是,我们应该将什么编码转换为此格式。因此,就有了第二种解决方案——把GBK格式的转换为ISO-8859-1格式。而且,有的人还说,必须得这么转。其实,之所以他们能这么说,我觉得完全是巧合。它的真正原理是,既然FTP协议规定的编码格式是“ISO-8859-1”,那么我们确实得将格式转换一下,然后等服务器收到文件时再自动转换为系统自带的编码格式,因此,关键不是规定为什么格式,而是取决于FTP服务器的编码格式。因此,如果FTP系统的编码格式为“GBK”时,第二种方式肯定会成功;但是,如果系统的编码格式为“UTF-8”时,那就会仍然出现乱码啦。所以,我们只能通过代码先获取系统的编码格式,然后通过此编码格式转换为ISO-8859-1的编码格式。获取方式如下:

private static String encoding = System.getProperty("file.encoding");

以上代码均通过自己测试,望能为大家解决一下问题!顺便提供一下FTP服务器搭建工具Serv-U,里面包含了注册机,需要的请点击 下载。如果注册时有什么问题请及时回复!

java ftp 上传下载相关推荐

  1. java实现的FTP上传下载客户端

    org.apache.commons.net.ftp.*中的FTPClient类实现的FTP上传下载功能: 需导入Apache的commos-net的jar包,若导入的是1.4版本的包,则FTPFil ...

  2. ftp. java. jdk_java实现ftp上传下载(jdk1.7以下)

    java实现ftp上传下载(jdk1.7以下)完整代码,复制可用 FTP实现代码: package com.util; import java.io.File; import java.io.File ...

  3. java ftp上传文件_jaVA使用FTP上传下载文件的问题

    为了实现 FTP上传下载,大概试了两个方法 sun.net.ftp.FtpClient org.apache.commons.net 一开始使用sun.net.ftp.FtpClient,结果发现唯一 ...

  4. 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 作者:宇的季节 cnblogs.com/chenkeyu/p/80 ...

  5. ftp上传-下载文件通用工具类,已实测

    话不多说直接上代码 package com.springboot.demo.utils;import lombok.extern.slf4j.Slf4j; import org.apache.comm ...

  6. linux curl 命令 http请求、下载文件、ftp上传下载

    1. curl 命令简介 cURL(CommandLine Uniform Resource Locator),是一个利用 URL 语法,在命令行终端下使用的网络请求工具,支持 HTTP.HTTPS. ...

  7. python get 下载 目录_python实现支持目录FTP上传下载文件的方法

    本文实例讲述了python实现支持目录FTP上传下载文件的方法.分享给大家供大家参考.具体如下: 该程序支持ftp上传下载文件和目录.适用于windows和linux平台. #!/usr/bin/en ...

  8. linux的ftp下载假死,记一次commons-net FTP上传下载卡死

    在利用apache的commons-net包,做FTP上传下载时,碰到了一个问题:在默认配置下,传输大文件会卡死. commons-net的maven依赖: commons-net commons-n ...

  9. python上传本地文件到ftp_python实现的简单FTP上传下载文件实例

    本文实例讲述了python实现的简单FTP上传下载文件的方法.分享给大家供大家参考.具体如下: python本身自带一个FTP模块,可以实现上传下载的函数功能. #!/usr/bin/env pyth ...

最新文章

  1. Richard Feynman, 挑战者号, 软件工程,自顶而下
  2. Python基础-模块
  3. 5 秒创建 k8s 集群[转]
  4. mysql slow time_mysql使用slow log
  5. matlab张量工具初步
  6. ASP.NET---- Microsoft .NET Pet Shop 3.x(-)
  7. 用贝叶斯定理解决三门问题并用Python进行模拟(Bayes‘ Rule Monty Hall Problem Simulation Python)
  8. I have to mention the search function at the
  9. 机器学习笔记【一】- 线性回归(末):统计学推导以及局部加权线性回归算法实例
  10. 基于java写的雷霆战机
  11. 操作系统不等于 Linux,六问操作系统新时代 | 1024 程序员节
  12. Quixel bridge无法导入到blender
  13. 新库上线 | CnOpenDataA股上市公司财务报表数据
  14. [.NET]CheckBoxList 用法
  15. Android 实现推送功能
  16. Chatbot项目的剖析
  17. 经典残局html,微信欢乐斗地主3月残局1-100关全攻略 3月残局图文攻略大全
  18. IIS7.5服务器上发布视频,不能在浏览器显示
  19. 高一计算机专业班主任工作总结,【班主任工作总结报告计算机材料】
  20. 报表与传统html优缺点,BI工具和报表有什么不同?你一定要懂这些区别

热门文章

  1. seo是做什么-程绩
  2. div rot grad
  3. 计算机期末总结ppt课件,计算机期末总结
  4. archlinux 安装matlab
  5. js鸡兔同笼35个头94只脚用 鸡有多少只兔有多少只?
  6. OTSU(最大类间方差法、大津算法)
  7. 电容的参数-详细描述
  8. 业务修养篇-业务理解有偏差,产品和开发如何达成共识?
  9. 动态规划-背包问题(1)
  10. uniapp前端向后端发送请求时,出现跨域问题的解决方法与原理