zoukankan      html  css  js  c++  java
  • ftp上传下载

    需要下载一个jar包 :commons-net-3.2.jar

    经过分析发现,linux环境与win环境的ftp操作有以下差别: 
    1、文件中的数据回车换行符不同 
    win的回车换行时:/r/n 
    linux的回车换行是:/n 

    导致上传 或下载的文件打不开

    那么在ftpclient登录成功后,和开始下载文件前设置传输类型即可。 
    ftpclient.login(user, password); 

    // 设置文件的传输类型,默认是ASCII,修改为二进制  
    ftpclient.setFileType(FTP.BINARY_FILE_TYPE); 

    package com.wang.tools;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;

    import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.net.ftp.FTP;
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPFile;
    import org.apache.commons.net.ftp.FTPReply;

    import com.wang.bean.Filexx;

    /**
    * ftp上传下载工具类
    */
    public class FtpUtil {

    /**
    * Description: 向FTP服务器上传文件
    * @param host FTP服务器hostname (IP地址)
    * @param port FTP服务器端口 (默认是21)
    * @param username FTP登录账号
    * @param password FTP登录密码
    * @param basePath FTP服务器基础目录 (根目录为空)
    * @param filePath FTP服务器文件存放路径。文件的路径为basePath+filePath
    *
    * 原因:FTP协议里面,规定文件名编码为iso-8859-1,所以目录名或文件名需要转码。
    * 解决方案:name=new String(name.getBytes("GBK"),"iso-8859-1"); 使用这个转码
    *
    * @param filename 上传到FTP服务器上的文件名
    * @param input 输入流
    * @return 成功返回true,否则返回false
    */
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
    String filePath, String filename, InputStream input) {
    boolean result = false;
    FTPClient ftp = new FTPClient();
    try {
    int reply;
    ftp.connect(host, port);// 连接FTP服务器
    // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
    boolean login = ftp.login(username, password);// 登录
    System.out.println("登录FTP是否成功:"+login);
    reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    return result;
    }
    //切换到上传目录
    if (!ftp.changeWorkingDirectory(basePath+filePath)) {
    //如果目录不存在创建目录
    String[] dirs = filePath.split("/");
    String tempPath = basePath;
    for (String dir : dirs) {
    if (null == dir || "".equals(dir)) continue;
    tempPath += "/" + dir;
    if (!ftp.changeWorkingDirectory(tempPath)) { //进不去目录,说明该目录不存在
    if (!ftp.makeDirectory(tempPath)) { //创建目录
    //如果创建文件目录失败,则返回
    System.out.println("创建文件目录"+tempPath+"失败");
    return result;
    } else {
    //目录存在,则直接进入该目录
    ftp.changeWorkingDirectory(tempPath);
    }
    }
    }
    }
    //设置上传文件的类型为二进制类型
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    //上传文件
    if (!ftp.storeFile(filename, input)) {
    return result;
    }
    input.close();
    ftp.logout();
    result = true;
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (ftp.isConnected()) {
    try {
    ftp.disconnect();
    } catch (IOException ioe) {
    }
    }
    }
    return result;
    }

    /**
    * Description: 从FTP服务器下载文件
    * @param host FTP服务器hostname
    * @param port FTP服务器端口
    * @param username FTP登录账号
    * @param password FTP登录密码
    * @param remotePath FTP服务器上的相对路径
    * @param fileName 要下载的文件名
    * @param localPath 下载后保存到本地的路径
    * @return
    */
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
    String fileName, String localPath,HttpServletResponse response) {
    boolean result = false;
    FTPClient ftp = new FTPClient();
    try {
    int reply;
    ftp.connect(host, port);
    // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
    ftp.login(username, password);// 登录
    // 设置文件的传输类型,默认是ASCII,修改为二进制
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    return result;
    }
    boolean changeWorkingDirectory = ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
    System.out.println("进入FTP服务器目录是否成功:"+changeWorkingDirectory);
    FTPFile[] fs = ftp.listFiles();
    for (FTPFile ff : fs) {
    if (ff.getName().equals(fileName)) {

    fileName=new String(fileName.getBytes("iso-8859-1"),"GBK");//转码成中文文件名输出
    //File localFile = new File(localPath + "/" + fileName);

    //OutputStream is = new FileOutputStream(localFile);
    response.reset();

    response.setHeader("Content-Disposition", "attachment; filename="
    + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
    response.setContentType("application/octet-stream; charset=utf-8");

    //ftp.retrieveFile(ff.getName(), is);//把文件内容通过输出流输出

    ftp.retrieveFile(ff.getName(), response.getOutputStream());//把文件内容通过输出流返回前端
    //is.close();
    }
    }

    ftp.logout();
    result = true;
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (ftp.isConnected()) {
    try {
    ftp.disconnect();
    } catch (IOException ioe) {
    }
    }
    }
    return result;
    }
    /**
    * Description: 从FTP服务器删除文件
    * @param host FTP服务器hostname
    * @param port FTP服务器端口
    * @param username FTP登录账号
    * @param password FTP登录密码
    * @param remotePath FTP服务器上的相对路径
    * @param fileName 要删除的文件名
    * @param
    * @return
    */
    public static boolean deleteFile(String host, int port, String username, String password, String path,
    String fileName) {
    boolean result = false;
    FTPClient ftp = new FTPClient();
    try {
    int reply;
    ftp.connect(host, port);
    // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
    ftp.login(username, password);// 登录
    // 设置文件的传输类型,默认是ASCII,修改为二进制
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    return result;
    }
    fileName=new String(fileName.getBytes("GBK"),"iso-8859-1");//防止下载的文件名为中文
    path=new String(path.getBytes("GBK"),"iso-8859-1");//防止ftp路径有中文文件夹
    boolean changeWorkingDirectory = ftp.changeWorkingDirectory(path);// 转移到FTP服务器目录
    System.out.println("进入FTP服务器目录是否成功:"+changeWorkingDirectory);//检查是否进入FTP服务器目录
    boolean deleteFile = ftp.deleteFile(fileName);//删除文件
    System.out.println("删除成功:"+deleteFile);
    ftp.logout();
    //result = true;
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (ftp.isConnected()) {
    try {
    ftp.disconnect();
    } catch (IOException ioe) {
    }
    }
    }
    return result;
    }
    /**
    * 获取ftp目录下所有文件的文件名和文件的最后修改时间
    * 并按照修改时间排序
    * @param host FTP服务器hostname
    * @param port FTP服务器端口
    * @param username FTP登录账号
    * @param password FTP登录密码
    * @param path 路径
    * @return
    */
    public static List<String[]> getFile(String host, int port, String username, String password,String path) {
    List<String[]> list = new ArrayList<String[]>();//存放文件名和文件最后修改时间的数组
    SimpleDateFormat getFileTime1 = new SimpleDateFormat("yyyy-MM-dd");
    String name=path;
    try {
    name=new String(name.getBytes("GBK"),"iso-8859-1");//防止ftp路径有中文文件夹
    } catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
    }

    String lastdate="";//存放文件最后修改时间格式为yyyy-mm-dd
    FTPClient ftp = new FTPClient();//ftp对象
    try {
    int reply;
    ftp.connect(host, port);//连接ftp
    // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
    ftp.login(username, password);// 登录
    reply = ftp.getReplyCode();
    //检查连接是否成功
    if (!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    }

    boolean changeWorkingDirectory = ftp.changeWorkingDirectory(name);// 转移到FTP服务器目录
    System.out.println("进入FTP服务器目录是否成功:"+changeWorkingDirectory);//true代表进入目录成功
    FTPFile[] fs = ftp.listFiles();

    ArrayList<Filexx> list1 =new ArrayList<Filexx>();//储存Filexx对象(存有文件名,date类型时间,long类型时间 排序用)
    String fileName;//文件名
    Long time;//时间
    for(int i=2;i<fs.length;i++) {
    Filexx f=new Filexx();
    fileName=fs[i].getName();
    fileName=new String(fileName.getBytes("iso-8859-1"),"GBK");//转码成中文文件名输出

    time = fs[i].getTimestamp().getTime().getTime();
    lastdate=getFileTime1.format(fs[i].getTimestamp().getTime());

    f.setFilename(fileName);
    f.setFiledate(lastdate);
    f.setTime(time);
    list1.add(f);
    // System.out.println(fileName+"%%%%"+lastdate+"%%%%%"+time);
    }
    getSortList_time(list1);//根据时间排序
    for(int j=0;j<list1.size();j++) {
    String[] fileWZ = {list1.get(j).getFilename(),list1.get(j).getFiledate()};
    list.add(fileWZ);
    }
    ftp.logout();

    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    if (ftp.isConnected()) {
    try {
    ftp.disconnect();
    } catch (IOException ioe) {
    }
    }
    }
    return list;
    }
    /*
    * 对Filexx的list集合排序
    * 根据时间降序排列
    */
    public static List<Filexx> getSortList_time(List<Filexx> list){
    Collections.sort(list, new Comparator<Filexx>() {
    @Override
    public int compare(Filexx o1, Filexx o2) {
    if(o1.getTime()>o2.getTime()){
    return -1;
    }
    if(o1.getTime()==o2.getTime()){
    return 0;
    }
    return 1;
    }
    });
    return list;
    }

    //ftp上传文件测试main函数
    public static void main(String[] args) throws UnsupportedEncodingException {
    try {
    FileInputStream in=new FileInputStream(new File("D:\人事档案\1311319.jpg"));
    String name="各部门组织架构/信息技术部";
    String fileName="1311319.jpg";
    name=new String(name.getBytes("GBK"),"iso-8859-1");//防止ftp路径有中文文件夹
    fileName=new String(fileName.getBytes("GBK"),"iso-8859-1");//防止下载的文件名为中文

    /**
    * 上传文件到ftp例子
    */
    boolean flag = uploadFile("ip地址", 端口号, "账号", "密码", "",name, fileName, in);

    /**
    * 从ftp下载文件例子

    * response是为了把下载的数据返回到前端
    */
    // boolean flag1=downloadFile("ip地址",端口号,"账号", "密码",name,fileName,"",response);
    // System.out.println(flag);
    // System.out.println(flag1);

    /**
    * 从ftp删除文件例子
    */
    boolean deleteFile = FtpUtil.deleteFile("IP地址",端口号,"账号", "密码",name,fileName);
    System.out.println(deleteFile);

    /**
    * 获取文件信息例子
    */
    // List<String[]> file = FtpUtil.getFile("IP地址",端口号,"账号", "密码","路径");;
    // for(String [] a: file) {
    // System.out.println(a[0]+":"+a[1]);
    // }
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    }
    }
    }

  • 相关阅读:
    实例属性 类属性 实例域 类域
    研究数据集
    static 静态域 类域 静态方法 工厂方法 he use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class 非访问修饰符
    accessor mothod mutator mothod 更改器方法 访问器方法 类的方法可以访问类的任何一个对象的私有域!
    上钻 下钻 切片 转轴 降采样
    识别会话
    Performance Tuning Using Linux Process Management Commands
    Secure Hash Algorithm 3
    grouped differently across partitions
    spark 划分stage Wide vs Narrow Dependencies 窄依赖 宽依赖 解析 作业 job stage 阶段 RDD有向无环图拆分 任务 Task 网络传输和计算开销 任务集 taskset
  • 原文地址:https://www.cnblogs.com/steven-snow/p/9396515.html
Copyright © 2011-2022 走看看