当前位置: 移动技术网 > IT编程>开发语言>Java > java实现FTP文件上传与文件下载

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

海贼王漫画720,杜凤华,mc佳瑶照片

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

第一种方式:

package com.cloudpower.util;

import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;

import sun.net.telnetinputstream;
import sun.net.telnetoutputstream;
import sun.net.ftp.ftpclient;

/**
 * java自带的api对ftp的操作
 * @title:ftp.java
 * @author: 周玲斌 
 */
public class ftp {
 /**
  * 本地文件名
  */
 private string localfilename;
 /**
  * 远程文件名
  */
 private string remotefilename;
 /**
  * ftp客户端
  */
 private ftpclient ftpclient;

 /**
  * 服务器连接
  * @param ip 服务器ip
  * @param port 服务器端口
  * @param user 用户名
  * @param password 密码
  * @param path 服务器路径
  * @author 周玲斌
  * @date 2012-7-11
  */
 public void connectserver(string ip, int port, string user,
   string password, string path) {
  try {
   /* ******连接服务器的两种方法*******/
   //第一种方法
//   ftpclient = new ftpclient();
//   ftpclient.openserver(ip, port);
   //第二种方法
   ftpclient = new ftpclient(ip);
   
   ftpclient.login(user, password);
   // 设置成2进制传输
   ftpclient.binary();
   system.out.println("login success!");
   if (path.length() != 0){
    //把远程系统上的目录切换到参数path所指定的目录
    ftpclient.cd(path);
   }
   ftpclient.binary();
  } catch (ioexception ex) {
   ex.printstacktrace();
   throw new runtimeexception(ex);
  }
 }
 /**
  * 关闭连接
  * @author 周玲斌
  * @date 2012-7-11
  */
 public void closeconnect() {
  try {
   ftpclient.closeserver();
   system.out.println("disconnect success");
  } catch (ioexception ex) {
   system.out.println("not disconnect");
   ex.printstacktrace();
   throw new runtimeexception(ex);
  }
 }
 /**
  * 上传文件
  * @param localfile 本地文件
  * @param remotefile 远程文件
  * @author 周玲斌
  * @date 2012-7-11
  */
 public void upload(string localfile, string remotefile) {
  this.localfilename = localfile;
  this.remotefilename = remotefile;
  telnetoutputstream os = null;
  fileinputstream is = null;
  try {
   //将远程文件加入输出流中
   os = ftpclient.put(this.remotefilename);
   //获取本地文件的输入流
   file file_in = new file(this.localfilename);
   is = new fileinputstream(file_in);
   //创建一个缓冲区
   byte[] bytes = new byte[1024];
   int c;
   while ((c = is.read(bytes)) != -1) {
    os.write(bytes, 0, c);
   }
   system.out.println("upload success");
  } catch (ioexception ex) {
   system.out.println("not upload");
   ex.printstacktrace();
   throw new runtimeexception(ex);
  } finally{
   try {
    if(is != null){
     is.close();
    }
   } catch (ioexception e) {
    e.printstacktrace();
   } finally {
    try {
     if(os != null){
      os.close();
     }
    } catch (ioexception e) {
     e.printstacktrace();
    }
   }
  }
 }
 
 /**
  * 下载文件
  * @param remotefile 远程文件路径(服务器端)
  * @param localfile 本地文件路径(客户端)
  * @author 周玲斌
  * @date 2012-7-11
  */
 public void download(string remotefile, string localfile) {
  telnetinputstream is = null;
  fileoutputstream os = null;
  try {
   //获取远程机器上的文件filename,借助telnetinputstream把该文件传送到本地。
   is = ftpclient.get(remotefile);
   file file_in = new file(localfile);
   os = new fileoutputstream(file_in);
   byte[] bytes = new byte[1024];
   int c;
   while ((c = is.read(bytes)) != -1) {
    os.write(bytes, 0, c);
   }
   system.out.println("download success");
  } catch (ioexception ex) {
   system.out.println("not download");
   ex.printstacktrace();
   throw new runtimeexception(ex);
  } finally{
   try {
    if(is != null){
     is.close();
    }
   } catch (ioexception e) {
    e.printstacktrace();
   } finally {
    try {
     if(os != null){
      os.close();
     }
    } catch (ioexception e) {
     e.printstacktrace();
    }
   }
  }
 }

 public static void main(string agrs[]) {

  string filepath[] = { "/temp/aa.txt", "/temp/regist.log"};
  string localfilepath[] = { "c:\\tmp\\1.txt","c:\\tmp\\2.log"};

  ftp fu = new ftp();
  /*
   * 使用默认的端口号、用户名、密码以及根目录连接ftp服务器
   */
  fu.connectserver("127.0.0.1", 22, "anonymous", "ieuser@", "/temp");
  
  //下载
  for (int i = 0; i < filepath.length; i++) {
   fu.download(filepath[i], localfilepath[i]);
  }
  
  string localfile = "e:\\号码.txt";
  string remotefile = "/temp/哈哈.txt";
  //上传
  fu.upload(localfile, remotefile);
  fu.closeconnect();
 }
}


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

第二种方式:

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("e:/号码.txt"));
   boolean flag = uploadfile("127.0.0.1", 21, "zlb","123", "/", "哈哈.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("127.0.0.1", 21, "zlb",
     "123", "/", "哈哈.txt", "d:/");
   system.out.println(flag);
  } catch (exception e) {
   e.printstacktrace();
  }
 }
 
 public static void main(string[] args) {
  ftpapche fa = new ftpapche();
  fa.testdownfile();
 }
}


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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网