{"id":545,"date":"2021-09-07T11:29:16","date_gmt":"2021-09-07T03:29:16","guid":{"rendered":"https:\/\/22pig.com\/?p=545"},"modified":"2021-09-07T11:29:16","modified_gmt":"2021-09-07T03:29:16","slug":"ftputil-java","status":"publish","type":"post","link":"http:\/\/22pig.com\/?p=545","title":{"rendered":"FtpUtil.java"},"content":{"rendered":"<p>package FTPDemo;<\/p>\n<p>import java.io.File;<br \/>\nimport java.io.FileInputStream;<br \/>\nimport java.io.FileOutputStream;<br \/>\nimport java.io.IOException;<br \/>\nimport java.io.OutputStream;<br \/>\nimport java.util.logging.Logger;<\/p>\n<p>import org.apache.commons.net.ftp.FTPClient;<br \/>\nimport org.apache.commons.net.ftp.FTPFile;<br \/>\nimport org.apache.commons.net.ftp.FTPReply;<\/p>\n<p>public class FtpUtil { <\/p>\n<p>private static FTPClient ftp;<\/p>\n<p>\/**<br \/>\n * \u83b7\u53d6ftp\u8fde\u63a5<br \/>\n * @param f<br \/>\n * @return<br \/>\n * @throws Exception<br \/>\n *\/<br \/>\npublic static boolean connectFtp(FtpConfig f) throws Exception{<br \/>\n    ftp=new FTPClient();<br \/>\n    boolean flag=false;<br \/>\n    if (f.getFtpPort()==null) {<br \/>\n        ftp.connect(f.getFtpHost(),21);<br \/>\n    }else{<br \/>\n        ftp.connect(f.getFtpHost(),f.getFtpPort());<br \/>\n    }<br \/>\n    ftp.login(f.getFtpUser(), f.getFtpPassword());<br \/>\n    ftp.enterLocalPassiveMode(); \/\/\u88ab\u52a8\u6a21\u5f0f<br \/>\n    int reply = ftp.getReplyCode();<br \/>\n    if (!FTPReply.isPositiveCompletion(reply)) {<br \/>\n          ftp.disconnect();<br \/>\n          return flag;<br \/>\n    }<br \/>\n    ftp.changeWorkingDirectory(f.getFtpPath());<br \/>\n    flag = true;<br \/>\n    return flag;<br \/>\n}<\/p>\n<p>\/**<br \/>\n * \u5173\u95edftp\u8fde\u63a5<br \/>\n *\/<br \/>\npublic static void closeFtp(){<br \/>\n  try {<br \/>\n      if (ftp!=null &#038;&#038; ftp.isConnected()) {<br \/>\n            ftp.logout();<br \/>\n            ftp.disconnect();<br \/>\n      }<br \/>\n  }catch (IOException e){<br \/>\n    e.printStackTrace();<br \/>\n  }<br \/>\n}<\/p>\n<p>\/**<br \/>\n * ftp\u4e0a\u4f20\u6587\u4ef6<br \/>\n * @param f<br \/>\n * @throws Exception<br \/>\n *\/<br \/>\npublic static void upload(File f) throws Exception{<br \/>\n    if (f.isDirectory()) {<br \/>\n        ftp.makeDirectory(f.getName());<br \/>\n        ftp.changeWorkingDirectory(f.getName());<br \/>\n        String[] files=f.list();<br \/>\n        for(String fstr : files){<br \/>\n            File file1=new File(f.getPath()+File.separator+fstr);<br \/>\n            if (file1.isDirectory()) {<br \/>\n                upload(file1);<br \/>\n                ftp.changeToParentDirectory();<br \/>\n            }else{<br \/>\n                File file2=new File(f.getPath()+File.separator+fstr);<br \/>\n                FileInputStream input=new FileInputStream(file2);<br \/>\n                ftp.storeFile(file2.getName(),input);<br \/>\n                input.close();<br \/>\n            }<br \/>\n        }<br \/>\n    }else{<br \/>\n        File file2=new File(f.getPath());<br \/>\n        FileInputStream input=new FileInputStream(file2);<br \/>\n        ftp.storeFile(file2.getName(),input);<br \/>\n        input.close();<br \/>\n    }<br \/>\n}<\/p>\n<p>\/**<br \/>\n * \u4e0b\u8f7d\u94fe\u63a5\u914d\u7f6e<br \/>\n * @param f<br \/>\n * @param localBaseDir \u672c\u5730\u76ee\u5f55<br \/>\n * @param remoteBaseDir \u8fdc\u7a0b\u76ee\u5f55<br \/>\n * @throws Exception<br \/>\n *\/<br \/>\npublic static void startDownDir(FtpConfig f,String localBaseDir,String remoteBaseDir) throws Exception{<br \/>\n    if (FtpUtil.connectFtp(f)) {<br \/>\n        try {<br \/>\n            FTPFile[] files = null;<br \/>\n            boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir);<br \/>\n            if (changedir) {<br \/>\n                ftp.setControlEncoding(&#8220;UTF-8&#8221;);<br \/>\n                files = ftp.listFiles();<br \/>\n                for (int i = 0; i < files.length; i++) { \n                     downloadFile(files[i], localBaseDir, remoteBaseDir); \n                } \n            }else{\n                 System.out.println(\"\u4e0d\u5b58\u5728\u7684\u76f8\u5bf9\u8def\u5f84\uff01\");\n            } \n        } catch (Exception e) { \n          e.printStackTrace();\n        } \n    }else{\n       System.out.println(\"\u8fde\u63a5\u5931\u8d25\");\n    }\n\n}\n\npublic static void startDownFile(FtpConfig f,String localBaseDir,String remoteFilePath) throws Exception{\n  if (FtpUtil.connectFtp(f)) {\n    try { \n      FileOutputStream outputStream = new FileOutputStream(localBaseDir + remoteFilePath); \n      ftp.retrieveFile(remoteFilePath, outputStream);\n      outputStream.flush();\n      outputStream.close();\n    } catch (Exception e) { \n      e.printStackTrace();\n    } \n  }else{\n    System.out.println(\"\u8fde\u63a5FTP\u670d\u52a1\u5668\u5931\u8d25\");\n  }\n\n}\n\n\n\/** \n * \n * \u4e0b\u8f7dFTP\u6587\u4ef6 \n * \u5f53\u4f60\u9700\u8981\u4e0b\u8f7dFTP\u6587\u4ef6\u7684\u65f6\u5019\uff0c\u8c03\u7528\u6b64\u65b9\u6cd5 \n * \u6839\u636e<b>\u83b7\u53d6\u7684\u6587\u4ef6\u540d\uff0c\u672c\u5730\u5730\u5740\uff0c\u8fdc\u7a0b\u5730\u5740<\/b>\u8fdb\u884c\u4e0b\u8f7d<br \/>\n *<br \/>\n * @param ftpFile<br \/>\n * @param relativeLocalPath \u4e0b\u8f7d\u5230\u672c\u5730\u7684\u7edd\u5bf9\u8def\u5f84<br \/>\n * @param relativeRemotePath \u8981\u4e0b\u8f7d\u7684\u8fdc\u7a0bftp\u670d\u52a1\u5668\u76f8\u5bf9\u8def\u5f84<br \/>\n *\/<br \/>\nprivate  static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) {<br \/>\n    if (ftpFile.isFile()) {<br \/>\n        if (ftpFile.getName().indexOf(&#8220;?&#8221;) == -1) {<br \/>\n            OutputStream outputStream = null;<br \/>\n            try {<br \/>\n                File locaFile= new File(relativeLocalPath+ ftpFile.getName());<br \/>\n                \/\/\u5224\u65ad\u6587\u4ef6\u662f\u5426\u5b58\u5728\uff0c\u5b58\u5728\u5219\u8fd4\u56de  or \u76f4\u63a5\u8986\u76d6<br \/>\n                if(locaFile.exists()){<br \/>\n                    return;<br \/>\n                }else{<br \/>\n                    outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName());<br \/>\n                    ftp.retrieveFile(ftpFile.getName(), outputStream);<br \/>\n                    outputStream.flush();<br \/>\n                }<br \/>\n            } catch (Exception e) {<br \/>\n                     e.printStackTrace();<br \/>\n            } finally {<br \/>\n                try {<br \/>\n                    if (outputStream != null){<br \/>\n                        outputStream.close();<br \/>\n                    }<br \/>\n                } catch (IOException e) {<br \/>\n                   e.printStackTrace();<br \/>\n                }<br \/>\n            }<br \/>\n        }<br \/>\n    } else {<br \/>\n        String newlocalRelatePath = relativeLocalPath + ftpFile.getName();<br \/>\n        String newRemote = relativeRemotePath + ftpFile.getName().toString();<br \/>\n        File fl = new File(newlocalRelatePath);<br \/>\n        if (!fl.exists()) {<br \/>\n            fl.mkdirs();<br \/>\n        }<br \/>\n        try {<br \/>\n            newlocalRelatePath = newlocalRelatePath+File.separator;<br \/>\n            newRemote = newRemote+File.separator;<br \/>\n            String currentWorkDir = ftpFile.getName().toString();<br \/>\n            \/\/System.out.println(currentWorkDir);<br \/>\n            boolean changedir = ftp.changeWorkingDirectory(currentWorkDir);<br \/>\n            if (changedir) {<br \/>\n                FTPFile[] files = null;<br \/>\n                files = ftp.listFiles();<br \/>\n                for (int i = 0; i < files.length; i++) { \n                    downloadFile(files[i], newlocalRelatePath, newRemote); \n                } \n            } \n            if (changedir){\n                ftp.changeToParentDirectory(); \n            } \n        } catch (Exception e) { \n            e.printStackTrace();\n        } \n    } \n} \n\n\npublic static void main(String[] args) throws Exception{  \n        FtpConfig f=new FtpConfig();\n        f.setFtpHost(\"192.168.3.100\");\n        f.setFtpPort(21);\n        f.setFtpUser(\"anonymous\");\n        f.setFtpPassword(\"\");\n        \/\/ f.setFtpPath(\"\/data1\/\");\/\/\u76f8\u5bf9\u8def\u5f84\n        FtpUtil.connectFtp(f);\n        File file = new File(\"E:\\\\data1\\\\physics.txt\");\n\n        \/\/FtpUtil.upload(file);\/\/\u628a\u6587\u4ef6\u4e0a\u4f20\u5728ftp\u4e0a\n        \/\/ FtpUtil.startDownFile(f, \"E:\/\",  \"physics.txt\");\n        FtpUtil.startDownDir(f, \"E:\/data1\/\",  \"\/data1\/\");\n\n   }  \n}\n<\/p>\n","protected":false},"excerpt":{"rendered":"<p>package FTPDemo; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.logging.Logger; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FtpUtil { private static FTPClient ftp; \/** * \u83b7\u53d6ftp\u8fde\u63a5 * @param f * @return * @throws Exception *\/ public static boolean connectFtp(FtpConfig f) throws Exception{ ftp=new FTPClient(); boolean flag=false; if (f.getFtpPort()==null) { ftp.connect(f.getFtpHost(),21); &#8230; <a title=\"FtpUtil.java\" class=\"read-more\" href=\"http:\/\/22pig.com\/?p=545\" aria-label=\"More on FtpUtil.java\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[],"class_list":["post-545","post","type-post","status-publish","format-standard","hentry","category-java"],"_links":{"self":[{"href":"http:\/\/22pig.com\/index.php?rest_route=\/wp\/v2\/posts\/545","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/22pig.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/22pig.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/22pig.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/22pig.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=545"}],"version-history":[{"count":0,"href":"http:\/\/22pig.com\/index.php?rest_route=\/wp\/v2\/posts\/545\/revisions"}],"wp:attachment":[{"href":"http:\/\/22pig.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=545"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/22pig.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=545"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/22pig.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=545"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}