在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

java实现FTP文件上传与文件下载

2016-7-29 15:37| 发布者: zhangjf| 查看: 674| 评论: 0

摘要: 本文实例为大家分享了两种java实现FTP文件上传下载的方式,供大家参考,具体内容如下 第一种方式: package com.cloudpower.util;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputSt ...

本文实例为大家分享了两种java实现FTP文件上传下载的方式,供大家参考,具体内容如下

第一种方式:

  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. }
复制代码


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

第二种方式:

  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");

以上代码均通过自己测试,望能为大家解决一下问题!

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-1 12:57

Copyright 2015-2025 djqfx

返回顶部