Java中實現FTP檔案上傳下載 涉及中文路徑以及中文檔案__Java

來源:互聯網
上載者:User
// 引用三個jar包  commons-net-1.4.1.jar   jakarta-oro-2.0.8.jar  log4j-1.2.17.jar
Ftp執行個體
<pre name="code" class="java">package com.ftp;/** * ftp連結常量 * */public class Ftp {private String ipAddr;//ip地址private Integer port;//連接埠號碼private String userName;//使用者名稱private String pwd;//密碼private String path;//aaa路徑public String getIpAddr() {return ipAddr;}public void setIpAddr(String ipAddr) {this.ipAddr = ipAddr;}public Integer getPort() {return port;}public void setPort(Integer port) {this.port = port;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String getPath() {return path;}public void setPath(String path) {this.path = path;}}




<pre name="code" class="java">package com.ftp;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPClientConfig;import org.apache.commons.net.ftp.FTPFile;import org.apache.commons.net.ftp.FTPReply;import org.apache.log4j.Logger;public class FtpUtil {private static Logger logger=Logger.getLogger(FtpUtil.class);private static FTPClient ftp;/** * 擷取FTP串連 * @param f * @return * @throws Exception */public static boolean connectFtp(Ftp f) throws Exception{ftp=new FTPClient();boolean flag=false;int reply;if (f.getPort()==null) {ftp.connect(f.getIpAddr(),21);}else{ftp.connect(f.getIpAddr(),f.getPort());}ftp.login(f.getUserName(), f.getPwd());ftp.setFileType(FTPClient.BINARY_FILE_TYPE);reply = ftp.getReplyCode();          if (!FTPReply.isPositiveCompletion(reply)) {                ftp.disconnect();                return flag;          }          ftp.changeWorkingDirectory(f.getPath());          flag = true;          return flag;}/** * 關閉FTP串連 */public static void closeFtp(){if (ftp!=null && ftp.isConnected()) {try {ftp.logout();ftp.disconnect();} catch (IOException e) {e.printStackTrace();}}}/** * ftp上傳檔案 * @param f * @throws Exception */public static void upload(File f) throws Exception{if (f.isDirectory()) {ftp.makeDirectory(f.getName());ftp.changeWorkingDirectory(f.getName());String[] files=f.list();for(String fstr : files){File file1=new File(f.getPath()+"/"+fstr);if (file1.isDirectory()) {upload(file1);ftp.changeToParentDirectory();}else{File file2=new File(f.getPath()+"/"+fstr);FileInputStream input=new FileInputStream(file2);ftp.storeFile(file2.getName(),input);input.close();}}}else{File file2=new File(f.getPath());FileInputStream input=new FileInputStream(file2);ftp.storeFile(file2.getName(),input);input.close();}}/** * 下載串連配置 * @param f * @param localBaseDir 本地目錄 * @param remoteBaseDir 遠程目錄 * @throws Exception */public static void startDown(Ftp f,String localBaseDir,String remoteBaseDir ) throws Exception{if (FtpUtil.connectFtp(f)) {        try {             FTPFile[] files = null;             boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir);             if (changedir) {             ftp.setControlEncoding("iso-8859-1");//注意編碼格式            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);            conf.setServerLanguageCode("zh");//中文                files = ftp.listFiles();                 for (int i = 0; i < files.length; i++) {                     try{                                             downloadFile(files[i], localBaseDir, remoteBaseDir);                     }catch(Exception e){                     logger.error(e);                     logger.error("<"+files[i].getName()+"下載失敗");                     }                 }             }         } catch (Exception e) {         logger.error(e);         logger.error("下載過程中出現異常");         } }else{logger.error("串連失敗!");}}/**      *      * 下載FTP檔案      * 當你需要下載FTP檔案的時候,調用此方法      * 根據--擷取的檔案名稱,本地地址,遠程地址--進行下載      * @param ftpFile      * @param relativeLocalPath      * @param relativeRemotePath  * @throws Exception      */     private  static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath) throws Exception {                         if (ftpFile.isFile()) {        String filename=new String(ftpFile.getName().getBytes("iso-8859-1"), "utf-8");//涉及到中文檔案System.out.println(filename);            if (ftpFile.getName().indexOf("?") == -1) {                 OutputStream outputStream = null;                 try {                     File locaFile= new File(relativeLocalPath+ filename);                     //若檔案已存在則返回                    if(locaFile.exists()){                     System.out.println("提示:目標檔案已存在。。。。");                        return;                     }else{                         outputStream = new FileOutputStream(relativeLocalPath+ filename);                                                ftp.retrieveFile(ftpFile.getName(), outputStream);                         outputStream.flush();                         outputStream.close();                     }                 } catch (Exception e) {                     logger.error(e);                } finally {                     try {                         if (outputStream != null){                             outputStream.close();                         }                    } catch (IOException e) {                        logger.error("輸出檔案流異常");                     }                 }             }         } else {             String newlocalRelatePath = relativeLocalPath + ftpFile.getName();             String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString());             File fl = new File(newlocalRelatePath);             if (!fl.exists()) {                 fl.mkdirs();             }             try {                 newlocalRelatePath = newlocalRelatePath + '/';                 newRemote = newRemote + "/";                 String currentWorkDir = ftpFile.getName().toString();                 boolean changedir = ftp.changeWorkingDirectory(currentWorkDir);                 if (changedir) {                     FTPFile[] files = null;                     files = ftp.listFiles();                     for (int i = 0; i < files.length; i++) {                         downloadFile(files[i], newlocalRelatePath, newRemote);                     }                 }                 if (changedir){                ftp.changeToParentDirectory();                 }             } catch (Exception e) {                 logger.error(e);            }         }     } public static void main(String[] args) throws Exception{  Ftp f=new Ftp();//ip地址f.setIpAddr("36.110.85.10");//ftp使用者名稱f.setUserName("p_center");//ftp密碼f.setPwd("ea65db2fa7f45672");//連接埠號碼f.setPort(21);//FtpUtil.connectFtp(f);//File file = new File("F:/test/com/test/Testng.java");  //FtpUtil.upload(file);//String local = "f:/";String remote ="/大連華訊/郵幣卡";String remoteUrl = new String(remote.getBytes("utf-8"), "iso-8859-1");//涉及到中文問題 根據系統實際編碼改變FtpUtil.startDown(f, local,  remoteUrl);System.out.println("ok");   }  }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.