设为首页 收藏本站
查看: 672|回复: 0

[经验分享] Java Ftp远程附件下载

[复制链接]

尚未签到

发表于 2016-6-8 12:00:19 | 显示全部楼层 |阅读模式
package com.a;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class A extends HttpServlet {
/**
  *
  */
private static final long serialVersionUID = -2785475707074908652L;
private FTPAgent ftpAgent = new FTPAgentImpl();
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
  
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  ftpAgent.connect("66.0.42.186", 21, "posp", "posp");
  String[] fileArray = ftpAgent.listFileNames("/posp/batch/file/report/20130628/20130628商户入账明细.tar");
  File[] file=ftpAgent.download("/posp/batch/file/report/20130628/", "/posp/temp/", fileArray);
  ftpAgent.disconnect();
  File filew=file[0];
  System.out.println("file.getName()="+filew.getName());
  response.setHeader("Content-disposition", "attachment; filename=" + toUtf8String(filew.getName()));
  response.setContentType("application/ms-excel; charset=\"utf-8\"");
  ServletOutputStream out = response.getOutputStream();
  try {
   writeFile(filew, out);
  } catch (Exception e) {
   e.printStackTrace();
  }
}



/**
  * 文件写入指定目录
  *
  * @param file
  * @param out
  * @throws Exception
  */
public static void writeFile(File file, OutputStream out) throws Exception {
  BufferedInputStream bis = null;
  try {
   bis = new BufferedInputStream(new FileInputStream(file));
   int len = 0;
   byte[] buf = new byte[512];
   while ((len = bis.read(buf)) != -1) {
    out.write(buf, 0, len);
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (bis != null)
    try {
     bis.close();
    } catch (IOException e) {

     e.printStackTrace();
    }
  }

}
/**
  * 导出文件防止文件名是中文时乱码的现象
  *
  * @param s
  * @return
  */
public static String toUtf8String(String s) {
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < s.length(); i++) {
   char c = s.charAt(i);
   if (c >= 0 && c <= 255) {
    sb.append(c);
   } else {
    byte[] b;
    try {
     b = Character.toString(c).getBytes("utf-8");
    } catch (Exception ex) {
     System.out.println(ex);
     b = new byte[0];
    }
    for (int j = 0; j < b.length; j++) {
     int k = b[j];
     if (k < 0)
      k += 256;
     sb.append("%" + Integer.toHexString(k).toUpperCase());
    }
   }
  }
  return sb.toString();
}
}

package com.a;


import java.io.File;
import java.io.IOException;
import java.text.ParseException;

import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FTPFile;
import com.enterprisedt.net.ftp.FileTransferClient;


public class FTPAgentImpl implements FTPAgent {

private String ip;

private int port;

private String userName;

private String password;

private FileTransferClient client;

public FTPAgentImpl() {
  this("", 21, "", "");
}

public FTPAgentImpl(String ip, int port, String userName, String password) {
  this.ip = ip;
  this.port = port;
  this.userName = userName;
  this.password = password;
  client = new FileTransferClient();
  client.getAdvancedSettings().setControlEncoding("GBK"); // FTP回显信息编码设为GBK
}

public void connect(String ip, int port, String userName, String password) {
  this.ip = ip;
  this.port = port;
  this.userName = userName;
  this.password = password;
  connect();
}

public void connect() {
  try {
//   System.out.println("ip:" + ip + ".port:" + port + ".name:" + userName + ".pass:" + password);
   client.setRemoteHost(ip);
   client.setRemotePort(port);
   client.setUserName(userName);
   client.setPassword(password);
   System.out.println("ip:" + ip + ".port:" + port + ".name:" + userName + ".pass:" + password);
   client.connect();
  } catch (FTPException e) {
     e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

/**
  * 关闭FTP连接
  */
public void disconnect() {
  try {
   client.disconnect();
  } catch (FTPException e) {
   System.out.println("断开FTP连接时报错");
  } catch (IOException e) {
   System.out.println("断开FTP连接时报错");
  }
}

public String[] listFileNames(String dir) {
  String[] fileNames = null;
  try {
   fileNames = client.directoryNameList(dir, false);
  } catch (FTPException e) {
   fileNames = new String[] {};
  } catch (IOException e) {
   e.printStackTrace();
  }
  return fileNames;
}


public FTPFile[] fileList(String dir) throws ParseException {
  FTPFile[] file = null;
  try {
   file = client.directoryList(dir);
  } catch (FTPException e) {
   file = new FTPFile[] {};
  } catch (IOException e) {
   e.printStackTrace();
  }
  return file;
}


public File download(String remoteDir, String localDir, String fileName) {
  try {
   System.out.println(localDir + fileName+"=="+remoteDir + fileName);
   client.downloadFile(localDir + fileName, remoteDir + fileName);
  } catch (FTPException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }

  return new File(localDir + fileName);
}

public File[] download(String remoteDir, String localDir, String[] fileNames) {
  if (fileNames == null || fileNames.length == 0)
   return new File[] {};
  File[] files = new File[fileNames.length];
  for (int i = 0; i < fileNames.length; i++){
   File file=new File(fileNames);
   System.out.println("fileNames="+file.getName());
   
   files = download(remoteDir, localDir, file.getName());
  }
  
  return files;
}






public void upload(File localFile, String remoteDir) {
  try {
   client.uploadFile(localFile.getPath(), remoteDir + localFile.getName());
  } catch (FTPException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

@Override
public File[] download(String[] fileNames) {
  // TODO Auto-generated method stub
  return null;
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-227853-1-1.html 上篇帖子: php 不重新编译 添加 ftp 模块 下篇帖子: Apache FTP 实用代码(转)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表