Java實現FTP檔案與檔案夾的上傳和下載1

來源:互聯網
上載者:User

標籤:rect   檢驗   success   檔案上傳   current   plog   相關   host   登入密碼   

Java實現FTP檔案與檔案夾的上傳和下載 http://www.cnblogs.com/winorgohome/archive/2016/11/22/6088013.html

  FTP 是File Transfer Protocol(檔案傳輸通訊協定)的英文簡稱,而中文簡稱為“文傳協議”。用於Internet上的控制檔案的雙向傳輸。同時,它也是一個應用程式(Application)。基於不同的作業系統有不同的FTP應用程式,而所有這些應用程式都遵守同一種協議以傳輸檔案。在FTP的使用當中,使用者經常遇到兩個概念:"下載"(Download)和"上傳"(Upload)。"下載"檔案就是從遠程主機拷貝檔案至自己的電腦上;"上傳"檔案就是將檔案從自己的電腦中拷貝至遠程主機上。用Internet語言來說,使用者可通過客戶機程式向(從)遠程主機上傳(下載)檔案。

  首先下載了Serv-U將自己的電腦設定為了FTP檔案伺服器,方便操作。下面代碼的使用都是在FTP伺服器已經建立,並且要在代碼中寫好FTP串連的相關資料才可以完成。

1.FTP檔案的上傳與下載(注意是單個檔案的上傳與下載)

 

import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import org.apache.commons.net.ftp.FTP;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPFile;import org.apache.commons.net.ftp.FTPReply;/** * 實現FTP檔案上傳和檔案下載 */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("D:/test02/list.txt"));            boolean flag = uploadFile("10.0.0.102", 21, "admin","123456", "/", "lis.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("10.0.0.102", 21, "admin",                    "123456", "/", "ip.txt", "E:/");            System.out.println(flag);        } catch (Exception e) {            e.printStackTrace();        }    }        public static void main(String[] args) {        FtpApche fa = new FtpApche();        fa.testDownFile();        fa.testUpLoadFromDisk();    }}

 2.FTP檔案夾的上傳與下載(注意是整個檔案夾)

package ftp;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.TimeZone;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 FTPTest_04 {    private FTPClient ftpClient;    private String strIp;    private int intPort;    private String user;    private String password;      private static Logger logger = Logger.getLogger(FTPTest_04.class.getName());      /* *      * Ftp建構函式      */      public FTPTest_04(String strIp, int intPort, String user, String Password) {        this.strIp = strIp;        this.intPort = intPort;        this.user = user;        this.password = Password;        this.ftpClient = new FTPClient();    }    /**      * @return 判斷是否登入成功      * */      public boolean ftpLogin() {        boolean isLogin = false;        FTPClientConfig ftpClientConfig = new FTPClientConfig();        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());        this.ftpClient.setControlEncoding("GBK");        this.ftpClient.configure(ftpClientConfig);        try {            if (this.intPort > 0) {                this.ftpClient.connect(this.strIp, this.intPort);            }else {                this.ftpClient.connect(this.strIp);            }            // FTP伺服器串連回答              int reply = this.ftpClient.getReplyCode();            if (!FTPReply.isPositiveCompletion(reply)) {                this.ftpClient.disconnect();                logger.error("登入FTP服務失敗!");                return isLogin;            }            this.ftpClient.login(this.user, this.password);            // 設定傳輸協議              this.ftpClient.enterLocalPassiveMode();            this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);            logger.info("恭喜" + this.user + "成功登陸FTP伺服器");            isLogin = true;        }catch (Exception e) {            e.printStackTrace();            logger.error(this.user + "登入FTP服務失敗!" + e.getMessage());        }        this.ftpClient.setBufferSize(1024 * 2);        this.ftpClient.setDataTimeout(30 * 1000);        return isLogin;    }      /**      * @退出關閉伺服器連結      * */      public void ftpLogOut() {        if (null != this.ftpClient && this.ftpClient.isConnected()) {            try {                boolean reuslt = this.ftpClient.logout();// 退出FTP伺服器                  if (reuslt) {                    logger.info("成功退出伺服器");                }            }catch (IOException e) {                e.printStackTrace();                logger.warn("退出FTP伺服器異常!" + e.getMessage());            }finally {                try {                    this.ftpClient.disconnect();// 關閉FTP伺服器的串連                  }catch (IOException e) {                    e.printStackTrace();                    logger.warn("關閉FTP伺服器的串連異常!");                }            }        }    }      /***      * 上傳Ftp檔案      * @param localFile 當地檔案      * @param romotUpLoadePath上傳伺服器路徑 - 應該以/結束      * */      public boolean uploadFile(File localFile, String romotUpLoadePath) {        BufferedInputStream inStream = null;        boolean success = false;        try {            this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改變工作路徑              inStream = new BufferedInputStream(new FileInputStream(localFile));            logger.info(localFile.getName() + "開始上傳.....");            success = this.ftpClient.storeFile(localFile.getName(), inStream);            if (success == true) {                logger.info(localFile.getName() + "上傳成功");                return success;            }        }catch (FileNotFoundException e) {            e.printStackTrace();            logger.error(localFile + "未找到");        }catch (IOException e) {            e.printStackTrace();        }finally {            if (inStream != null) {                try {                    inStream.close();                }catch (IOException e) {                    e.printStackTrace();                }            }        }        return success;    }      /***      * 下載檔案      * @param remoteFileName   待下載檔案名稱      * @param localDires 下載到當地那個路徑下      * @param remoteDownLoadPath remoteFileName所在的路徑      * */        public boolean downloadFile(String remoteFileName, String localDires,              String remoteDownLoadPath) {        String strFilePath = localDires + remoteFileName;        BufferedOutputStream outStream = null;        boolean success = false;        try {            this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);            outStream = new BufferedOutputStream(new FileOutputStream(                      strFilePath));            logger.info(remoteFileName + "開始下載....");            success = this.ftpClient.retrieveFile(remoteFileName, outStream);            if (success == true) {                logger.info(remoteFileName + "成功下載到" + strFilePath);                return success;            }        }catch (Exception e) {            e.printStackTrace();            logger.error(remoteFileName + "下載失敗");        }finally {            if (null != outStream) {                try {                    outStream.flush();                    outStream.close();                }catch (IOException e) {                    e.printStackTrace();                }            }        }        if (success == false) {            logger.error(remoteFileName + "下載失敗!!!");        }        return success;    }      /***      * @上傳檔案夾      * @param localDirectory      *            當地檔案夾      * @param remoteDirectoryPath      *            Ftp 伺服器路徑 以目錄"/"結束      * */      public boolean uploadDirectory(String localDirectory,              String remoteDirectoryPath) {        File src = new File(localDirectory);        try {            remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";            boolean makeDirFlag = this.ftpClient.makeDirectory(remoteDirectoryPath);            System.out.println("localDirectory : " + localDirectory);            System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);            System.out.println("src.getName() : " + src.getName());            System.out.println("remoteDirectoryPath : " + remoteDirectoryPath);            System.out.println("makeDirFlag : " + makeDirFlag);            // ftpClient.listDirectories();        }catch (IOException e) {            e.printStackTrace();            logger.info(remoteDirectoryPath + "目錄建立失敗");        }        File[] allFile = src.listFiles();        for (int currentFile = 0;currentFile < allFile.length;currentFile++) {            if (!allFile[currentFile].isDirectory()) {                String srcName = allFile[currentFile].getPath().toString();                uploadFile(new File(srcName), remoteDirectoryPath);            }        }        for (int currentFile = 0;currentFile < allFile.length;currentFile++) {            if (allFile[currentFile].isDirectory()) {                // 遞迴                  uploadDirectory(allFile[currentFile].getPath().toString(),                          remoteDirectoryPath);            }        }        return true;    }      /***      * @下載檔案夾      * @param localDirectoryPath本地地址      * @param remoteDirectory 遠程檔案夾      * */      public boolean downLoadDirectory(String localDirectoryPath,String remoteDirectory) {        try {            String fileName = new File(remoteDirectory).getName();            localDirectoryPath = localDirectoryPath + fileName + "//";            new File(localDirectoryPath).mkdirs();            FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);            for (int currentFile = 0;currentFile < allFile.length;currentFile++) {                if (!allFile[currentFile].isDirectory()) {                    downloadFile(allFile[currentFile].getName(),localDirectoryPath, remoteDirectory);                }            }            for (int currentFile = 0;currentFile < allFile.length;currentFile++) {                if (allFile[currentFile].isDirectory()) {                    String strremoteDirectoryPath = remoteDirectory + "/"+ allFile[currentFile].getName();                    downLoadDirectory(localDirectoryPath,strremoteDirectoryPath);                }            }        }catch (IOException e) {            e.printStackTrace();            logger.info("下載檔案夾失敗");            return false;        }        return true;    }    // FtpClient的Set 和 Get 函數      public FTPClient getFtpClient() {        return ftpClient;    }    public void setFtpClient(FTPClient ftpClient) {        this.ftpClient = ftpClient;    }          public static void main(String[] args) throws IOException {        FTPTest_04 ftp=new FTPTest_04("10.0.0.102",21,"admin","123456");        ftp.ftpLogin();        System.out.println("1");        //上傳檔案夾          boolean uploadFlag = ftp.uploadDirectory("D:\\test02", "/"); //如果是admin/那麼傳的就是所有檔案,如果只是/那麼就是傳檔案夾        System.out.println("uploadFlag : " + uploadFlag);        //下載檔案夾          ftp.downLoadDirectory("d:\\tm", "/");        ftp.ftpLogOut();    }}

Java實現FTP檔案與檔案夾的上傳和下載1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.