您的位置:首页 > 编程语言 > Java开发

springmvc+mybatis+html 下将查询数据以excell形式上传到ftp(下)

2017-06-07 19:08 399 查看
上节讲到的是从数据库中查询相应的结果以excell形式写到ftp服务器上,今天又试了试从ftp上将excell 文件下载到本地目录,一开始的时候遇到了中文乱码问题,文件名中含有中文下载下来文件名为乱码,以下贴出核心代码

1 package com.ninefbank.smallpay.admin.util;
2
3 import java.io.BufferedOutputStream;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.OutputStream;
9
10 import org.apache.commons.lang3.StringUtils;
11 import org.apache.commons.net.ftp.FTPClient;
12 import org.apache.commons.net.ftp.FTPClientConfig;
13 import org.apache.commons.net.ftp.FTPFile;
14 import org.apache.commons.net.ftp.FTPReply;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17
18 import com.jcraft.jsch.Channel;
19 import com.jcraft.jsch.ChannelSftp;
20 import com.jcraft.jsch.JSch;
21 import com.jcraft.jsch.Session;
22 import com.ninefbank.smallpay.admin.common.Ftp;
23 import com.ninefbank.smallpay.common.util.DateUtil;
24 import com.ninefbank.smallpay.common.vo.FtpRequest;
25
26 public class FtpUtils {
27     private static Logger logger = LoggerFactory.getLogger(FtpUtils.class);
28     private static FTPClient ftp;
29     private static String LOCAL_CHARSET = "GBK";
30
31
32     /* 获取ftp连接
33      * @param f
34      * @return
35      * @throws Exception
36      */
37     public static boolean connectFtp(Ftp f) throws Exception{
38         ftp=new FTPClient();
39         boolean flag=false;
40         int reply;
41         if (f.getPort()==null) {
42             ftp.connect(f.getIpAddr(),21);
43         }else{
44             ftp.connect(f.getIpAddr(),f.getPort());
45         }
46         ftp.login(f.getUserName(), f.getPwd());
47         ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
48         reply = ftp.getReplyCode();
49         if (!FTPReply.isPositiveCompletion(reply)) {
50               ftp.disconnect();
51               return flag;
52         }
53         ftp.changeWorkingDirectory(f.getPath());
54         flag = true;
55         return flag;
56     }
57      /* 下载链接配置
58       * @param f
59       * @param localBaseDir 本地目录
60       * @param remoteBaseDir 远程目录
61       * @throws Exception
62       */
63      public static void startDown(Ftp f,String localBaseDir,String remoteBaseDir ,FtpRequest reqs) throws Exception{
64          if (FtpUtils.connectFtp(f)) {
65
66              try {
67                  String ip = reqs.getIp();
68                  int port = Integer.parseInt(reqs.getPort());
69                  String userName = reqs.getUserName();
70                  String userPwd = reqs.getPwd();
71                  String path = reqs.getDownloadPath();
72                  String fileName = reqs.getFileName();
73                  String localPath = reqs.getLocalPath();
74                  FTPFile[] files = null;
75                  FTPClient ftpClient = new FTPClient();
76                  ftpClient.connect(ip, port);
77                  // 登录
78                  ftpClient.login(userName, userPwd);
79                  // 设置传输协议
80                  ftpClient.setRemoteVerificationEnabled(false);
81                  ftpClient.enterLocalPassiveMode();
82                  ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
83                  ftpClient.setListHiddenFiles(true);
84 //                 ftpClient.configure(new FTPClientConfig(FTPClientConfig.SYST_UNIX));
85                  if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
86                          "OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
87                          LOCAL_CHARSET = "UTF-8";
88                          }
89                  ftpClient.setControlEncoding(LOCAL_CHARSET);
90                  boolean changedir = ftpClient.changeWorkingDirectory(remoteBaseDir);
91                  if (changedir) {
92
93
94 //                     ftp.setControlEncoding("GBK");
95
96                      files = ftpClient.listFiles();
97                      for (int i = 0; i < files.length; i++) {
98                          try{
99                              if(fileName.equals(files[i].getName())){
100                                  downloadFile(ftpClient,files[i], localBaseDir, remoteBaseDir);
101                              }
102
103                          }catch(Exception e){
104                              logger.error("异常信息:"+e);
105                              logger.error("<"+files[i].getName()+">下载失败");
106                          }
107                      }
108                  }
109              } catch (Exception e) {
110                  logger.error("异常信息:"+e);
111                  logger.error("下载过程中出现异常");
112              }
113          }else{
114              logger.error("链接失败!");
115          }
116
117      }
118
119
120      /**
121       *
122       * 下载FTP文件
123       * 当你需要下载FTP文件的时候,调用此方法
124       * 根据<b>获取的文件名,本地地址,远程地址</b>进行下载
125       *
126       * @param ftpFile
127       * @param relativeLocalPath
128       * @param relativeRemotePath
129       */
130      private  static void downloadFile(FTPClient ftpClient,FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) {
131          if (ftpFile.isFile()) {
132              if (ftpFile.getName().indexOf("?") == -1) {
133                  OutputStream outputStream = null;
134                  try {
135                       String f= new String(ftpFile.getName().getBytes("GBK"), "iso-8859-1");
136                      File locaFile= new File(relativeLocalPath+ ftpFile.getName());
137                      //判断文件是否存在,存在则返回
138                      if(locaFile.exists()){
139                          return;
140                      }else{
141                          outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName());
142                          ftpClient.retrieveFile(new String(ftpFile.getName().getBytes("GBK"),"ISO-8859-1"), outputStream);
143                          outputStream.flush();
144                          outputStream.close();
145                      }
146                  } catch (Exception e) {
147                      logger.error("异常信息:"+e);
148                  } finally {
149                      try {
150                          if (outputStream != null){
151                              outputStream.close();
152                          }
153                      } catch (IOException e) {
154                         logger.error("输出文件流异常");
155                      }
156                  }
157              }
158          }
159      }
160
161 }


调用处:

FtpUtils.uploadFTP(req);
Ftp f=new Ftp();
f.setIpAddr(DataBaseConst.FTP_FEE_IP);
f.setUserName(DataBaseConst.FTP_FEE_USERNAME);
f.setPwd(DataBaseConst.FTP_FEE_PASSWORD);

String ftpPath = DataBaseConst.FTP_FEE_PATH + newFilePath + currDate8 + "/";

FtpRequest req = new FtpRequest();
req.setIp(DataBaseConst.FTP_FEE_IP);
req.setPort(DataBaseConst.FTP_FEE_PORT);
req.setUserName(DataBaseConst.FTP_FEE_USERNAME);
req.setPwd(DataBaseConst.FTP_FEE_PASSWORD);
req.setDownloadPath(DataBaseConst.FTP_FEE_PATH + newFilePath);
req.setFileName(branchFileName);
req.setLocalPath(localPath);

FtpUtils.startDown(f, "e:/", ftpPath,req);

代码我也没怎么优化,我贴这也是为了提醒自己下载的时候乱码怎么解决
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: