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

    FTPUtils.java 上传下载

      1 package com.demo.cronmodule.utils;
      2 
      3 import com.alibaba.fastjson.JSON;
      4 import com.demo.basebusiness.http.vo.ResultVo;
      5 import com.demo.qs.node.protocol.FtpProtocolUtil;
      6 import com.demo.qs.node.protocol.StatusResult;
      7 import org.apache.commons.logging.Log;
      8 import org.apache.commons.logging.LogFactory;
      9 import org.apache.commons.net.ftp.FTP;
     10 import org.apache.commons.net.ftp.FTPClient;
     11 import org.apache.commons.net.ftp.FTPFile;
     12 import org.apache.commons.net.ftp.FTPReply;
     13 import org.springframework.stereotype.Service;
     14 
     15 import javax.servlet.http.HttpServletResponse;
     16 import javax.servlet.http.HttpServletResponseWrapper;
     17 import java.io.*;
     18 import java.net.URLEncoder;
     19 import java.rmi.Remote;
     20 import java.util.ArrayList;
     21 import java.util.List;
     22 import java.util.zip.ZipEntry;
     23 import java.util.zip.ZipOutputStream;
     24 
     25 /**
     26  * @ClassName FtpApche
     27  * @Description
     28  * @Author username
     29  * @Date 2020/4/30  14:20
     30  */
     31 public class FtpApcheUtil {
     32     
     33     private static Log logger = LogFactory.getLog(FtpApcheUtil.class);
     34     private static String encoding = System.getProperty("file.encoding");
     35 
     36     public  String ip="192.168.50.88";
     37     public  int port=2121;
     38     public  String username="admin";
     39     public  String password="admin";
     40     public  String remotePath="/";
     41 
     42     private static FTPClient ftpClient = new FTPClient();
     43 
     44     public static FtpApcheUtil getInstance(String ip, int port, String username, String password){
     45         return new FtpApcheUtil(ip, port, username, password);
     46     }
     47     private FtpApcheUtil (String ip, int port, String username, String password){
     48         /* @param ip      FTP服务器hostname
     49          * @param port     FTP服务器端口
     50          * @param username FTP登录账号
     51          * @param password FTP登录密码
     52          */
     53         init(ip, port, username, password);
     54     }
     55 
     56     public void init(String ip, int port, String username, String password) {
     57         this.ip = ip;
     58         this.port = port;
     59         this.username = username;
     60         this.password = password;
     61     }
     62     public boolean connect(){
     63         try {
     64 
     65             int reply;
     66             ftpClient.connect(this.ip, this.port);// 连接FTP服务器
     67             //ftpClient.connect(url);  //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
     68             // 登录
     69             ftpClient.login(this.username, this.password);
     70             ftpClient.setControlEncoding(encoding);
     71             // 检验是否连接成功
     72             reply = ftpClient.getReplyCode();
     73             if (!FTPReply.isPositiveCompletion(reply)) {
     74                 logger.info("FTP server refused connection");
     75                 ftpClient.disconnect();
     76                 return false;
     77             }
     78             return true;
     79         } catch (IOException e) {
     80             logger.error("ftpClient.connect error",e);
     81             return false;
     82         }
     83     };
     84     /**
     85      * Description: 向FTP服务器上传文件
     86      *
     87      * @param path     FTP服务器保存目录,如果是根目录则为“/”
     88      * @param filename 上传到FTP服务器上的文件名
     89      * @param input    本地文件输入流
     90      * @return 成功返回true,否则返回false
     91      * @Version1.0
     92      */
     93     public boolean uploadFile( String path, String filename, InputStream input) {
     94         boolean result = false;
     95         try {
     96 
     97             boolean connectSucceess=connect();
     98             if(!connectSucceess){
     99                 return result;
    100             }
    101             // 转移工作目录至指定目录下
    102             boolean change = ftpClient.changeWorkingDirectory(path);
    103             ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    104             if (change) {
    105                 result = ftpClient.storeFile(new String(filename.getBytes(encoding), "iso-8859-1"), input);
    106                 if (result) {
    107                     logger.info("上传成功");
    108                 }
    109             }
    110             input.close();
    111             ftpClient.logout();
    112         } catch (IOException e) {
    113             logger.error("FtpApcheUtil.uploadFile catch IOException::",e);
    114         } finally {
    115             if (ftpClient.isConnected()) {
    116                 try {
    117                     ftpClient.disconnect();
    118                 } catch (IOException e) {
    119                     logger.error("FtpApcheUtil.uploadFile finally IOException:",e);
    120                 }
    121             }
    122         }
    123         return result;
    124     }
    125 
    126     /**
    127      * 将本地文件上传到FTP服务器上
    128      */
    129     public void doUpLoadFromDisk(String sourcePath,String sourceFileName,String targetPath,String targetFileName) {
    130         try {
    131             String sourceFile=sourcePath+sourceFileName;
    132             FileInputStream in = new FileInputStream(new File(sourceFile));
    133             boolean flag = uploadFile(targetPath, targetFileName, in);
    134             if(!flag){
    135                 logger.info("upload file failed");
    136             }
    137         } catch (Exception e) {
    138             logger.error("doUpLoadFromDisk Exception:",e);
    139         }
    140     }
    141 
    142 
    143     /**
    144      * Description: 从FTP服务器下载文件
    145      *
    146      * @param remotePath FTP服务器上的相对路径
    147      * @param fileName   要下载的文件名
    148      * @param localPath  下载后保存到本地的路径
    149      * @return
    150      * @Version1.0
    151      */
    152     public boolean downFile(String remotePath, String fileName,
    153                                    String localPath) {
    154         boolean result = false;
    155         try {
    156             /*
    157              *  为了上传和下载中文文件,有些地方建议使用以下两句代替
    158              *  new String(remotePath.getBytes(encoding),"iso-8859-1")转码。
    159              *  经过测试,通不过。
    160              */
    161 //            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
    162 //            conf.setServerLanguageCode("zh");
    163             boolean connectSucceess=connect();
    164             if(!connectSucceess){
    165                 return result;
    166             }
    167             // 转移到FTP服务器目录至指定的目录下
    168             ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding), "iso-8859-1"));
    169             // 设置文件传输类型为二进制
    170             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    171             // 获取文件列表
    172             FTPFile[] fs = ftpClient.listFiles();
    173             for (FTPFile ff : fs) {
    174                 if (ff.getName().equals(fileName)) {
    175                     File localFile = new File(localPath + "/" + ff.getName());
    176                     OutputStream is = new FileOutputStream(localFile);
    177                     ftpClient.retrieveFile(ff.getName(), is);
    178                     is.close();
    179                 }
    180             }
    181             ftpClient.logout();
    182             result = true;
    183         } catch (IOException e) {
    184             logger.error("downFile file failed catch:",e);
    185         } finally {
    186             if (ftpClient.isConnected()) {
    187                 try {
    188                     ftpClient.disconnect();
    189                 } catch (IOException ioe) {
    190                     logger.error("downFile file failed finally:",ioe);
    191                 }
    192             }
    193         }
    194         return result;
    195     }
    196 
    197     /**
    198      * 将FTP服务器上文件下载到本地
    199      */
    200     public void doDownFile(String localPath,String remotePath ,String fileName) {
    201         try {
    202             String rename ="test_ftp2.au3";
    203             localPath="C:\Users\username";  //下载至本地文件夹
    204             init(ip, port, username, password);
    205             boolean flag = downFile(remotePath, fileName, localPath);
    206             System.out.println(flag);
    207         } catch (Exception e) {
    208             logger.error("testDownFile:",e);
    209         }
    210     }
    211 /**
    212      * 实现文件打包压缩下载
    213      *
    214      * @param zipname       压缩包的文件名
    215      * @param ftpRemotePath ftp文件路径
    216      * @param ftpFileList   要下载的文件名集合
    217      * @param namelist      压缩后的文件名集合
    218      */
    219     public ResultVo<Object> ftpDownloadZipFile(ResultVo<Object> resultVo,String zipname, String ftpRemotePath, String localPath, List<String> ftpFileList, List<String> namelist) {
    220         boolean connectSucceess = connect();
    221         if (!connectSucceess) {
    222             resultVo.setCode(ResultVo.CODE_FAIL);
    223             resultVo.setMsg("连接FTP服务器失败");
    224             return resultVo;
    225         }
    226         FTPClient ftp = this.ftpClient;
    227         try {
    228             ftp.enterLocalPassiveMode();
    229             // 转移到FTP服务器目录至指定的目录下
    230             ftpClient.changeWorkingDirectory(new String(ftpRemotePath.getBytes(encoding), "iso-8859-1"));
    231             // 设置文件传输类型为二进制
    232             ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
    233 
    234             byte[] buf = new byte[1024];
    235             Set<String> failFileSet = new HashSet<>();
    236             Set<String> successFileSet = new HashSet<>();
    237 
    238             File zipFile =null;
    239             ZipOutputStream zipOut = null;
    240             for (int i = 0; i < ftpFileList.size(); i++) {
    241 
    242                 InputStream bis = ftp.retrieveFileStream(ftpFileList.get(i));
    243                 if (bis == null) {
    244                     failFileSet.add(ftpFileList.get(i));
    245                 } else {
    246                     if(zipFile==null) {
    247                         zipFile = new File(localPath + "/" + zipname);
    248                         zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
    249                     }
    250                     ZipEntry entry = new ZipEntry(namelist.get(i));//重命名
    251                     zipOut.putNextEntry(entry);
    252                     int readLen = -1;
    253                     while ((readLen = bis.read(buf, 0, 1024)) != -1) {
    254                         zipOut.write(buf, 0, readLen);
    255                     }
    256                     zipOut.closeEntry();
    257                     bis.close();
    258                     ftp.completePendingCommand();
    259                     //调用ftp.retrieveFileStream这个接口后,一定要手动close掉返回的InputStream,然后再调用completePendingCommand方法
    260                     // ,若不是按照这个顺序,则会导致后面对FTPClient的操作都失败
    261                 }
    262             }
    263             if(successFileSet.size()==0){
    264                 resultVo.setCode(ResultVo.CODE_FAIL);
    265                 resultVo.setMsg("下载失败,文件不存在:"+ String.join(",", failFileSet));
    266             }
    267             else if (failFileSet.size() > 0) {
    268                 resultVo.setCode(ResultVo.CODE_SUCCESS);
    269                 resultVo.setMsg("部分下载失败,以下文件不存在:"+ String.join(",", failFileSet));
    270             }
    271             if(zipOut!=null)
    272                 zipOut.close();
    273             ftp.logout();
    274             resultVo.setCode(ResultVo.CODE_SUCCESS);
    275             resultVo.setMsg(ResultVo.MSG_SUCCESS);
    276             //删除压缩包 zipFile.delete();
    277         } catch (Exception e) {
    278             resultVo.setCode(ResultVo.CODE_FAIL);
    279             resultVo.setMsg("FTP下载失败");
    280             logger.error("FTP下载失败: ", e);
    281         }
    282         return resultVo;
    283     }
    284 
    285 //普通springboot下载
    286  public ResultVo<Object> downloadFile(ResultVo<Object> resultVo, HttpServletResponse response, String zipname, String serverPath) {
    287         FileInputStream fis = null;
    288         BufferedInputStream bis = null;
    289         try {
    290             //下载
    291             byte[] buffer = new byte[1024];
    292 
    293             // 清除buffer缓存
    294             response.reset();
    295             response.setHeader("content-type", "application/octet-stream");
    296             response.setContentType("application/octet-stream");
    297 //            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipname, "UTF-8"));
    298 
    299             response.setHeader("Content-Disposition", "attachment; filename="
    300                     + URLEncoder.encode(zipname, encoding));// + ".zip"
    301             response.setHeader("Pragma", "no-cache");
    302             response.setHeader("Cache-Control", "no-cache");
    303             response.setDateHeader("Expires", 0);
    304             File file = new File(serverPath + zipname);
    305             fis = new FileInputStream(file);
    306             bis = new BufferedInputStream(fis);
    307             OutputStream os = response.getOutputStream();
    308             int i = 0;
    309             while ((i = bis.read(buffer)) != -1) {
    310                 os.write(buffer, 0, i);
    311                 os.flush();
    312             }
    313             resultVo.setCode(ResultVo.CODE_SUCCESS);
    314             resultVo.setMsg(ResultVo.MSG_SUCCESS);
    315             //删除压缩包
    316             //zipFile.delete();
    317         } catch (Exception e) {
    318             resultVo.setCode(ResultVo.CODE_FAIL);
    319             resultVo.setMsg("服务器文件下载失败");
    320             logger.error("文件打包下载有误: ", e);
    321         } finally {
    322             if (bis != null) {
    323                 try {
    324                     bis.close();
    325                 } catch (IOException e) {
    326                 }
    327             }
    328             if (fis != null) {
    329                 try {
    330                     fis.close();
    331                 } catch (IOException e) {
    332                 }
    333             }
    334 
    335             return resultVo;
    336         }
    337     }
    338 
    339     public static void main(String[] args) {
    340           String ip="192.168.50.88";
    341           int port=2121;
    342           String username="admin";
    343           String password="admin";
    344           String remotePath="/";
    345         List<String> ftpFileList=new ArrayList(){{
    346             add("test_ftp1.au3");
    347             add("test.au3");
    348         }};
    349         String zipName="test1.zip";
    350         FtpApcheUtil fa = FtpApcheUtil.getInstance(ip, port, username, password);
    351         String localPath="C:\Users\username";
    352         fa.zipDownloadFile(zipName,remotePath,localPath,ftpFileList,ftpFileList);
    353 /*        FtpProtocolUtil p = FtpProtocolUtil.getInstance();
    354             FtpApcheUtil ftpApcheUtil = FtpApcheUtil.getInstance();
    355             ftpApcheUtil.testUpLoadFromDisk();*/
    356         /*  boolean connect = p.connect(ip, port, username, password);
    357         List<StatusResult> results= p.upload("C:\Users\username\", "test_ftp1.au3", remotePath);*/
    358       /*  String localName ="test_ftp2.au3";
    359         String rename ="test_ftp1.au3";
    360         String localPath="C:\Users\username";
    361         StatusResult results = p.download(localPath,localName,remotePath,rename,true);
    362         logger.info(JSON.toJSONString(results));*/
    363     }
    364 
    365     
    366 }
    View Code

    原文链接:https://blog.csdn.net/qq837993702/article/details/81982186

    https://blog.csdn.net/chinaxiaofeng8/article/details/82110177

    实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1、通过JDK自带的API实现;2、通过Apache提供的API是实现。

    第一种方式

    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();
        }
    }
    View Code

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

    第二种方式

    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();
        }
    }
    View Code

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

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

    以上代码均通过自己测试,望能为大家解决一下问题! 
    ————————————————
    原文链接:https://blog.csdn.net/chinaxiaofeng8/article/details/82110177

  • 相关阅读:
    判断php变量是否定义,是否为空
    HTTP Client 编写
    推荐《冒号课堂——编程范式与OOP思想》
    一些免费的HTML编辑器
    如何判断mysql中数据表中两个列之间的相同记录和不同记录
    PostgreSQL 8.4, SQL Server 2008, MySQL 5.1比较
    JDBC纵览
    使用jdbc连接sql数据库
    关于PHP中变量的判定
    如何判断数据库中是否存在一个数据表
  • 原文地址:https://www.cnblogs.com/personsiglewine/p/12816814.html
Copyright © 2011-2022 走看看