java實現連接ftp服務器並下載文件到本地


1.pom.xml引入jar包

        <!--ftp-->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>

2.連接ftp服務器方法

 /** * 連接ftp服務器 * @param ip ftp地址 * @param port 端口 * @param username 賬號 * @param password 密碼 * @return * @throws IOException */
    public static FTPClient ftpConnection(String ip,String port, String username, String password) throws IOException { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(ip, Integer.parseInt(port)); ftpClient.login(username, password); int replyCode = ftpClient.getReplyCode(); //是否成功登錄服務器
            if(!FTPReply.isPositiveCompletion(replyCode)) { ftpClient.disconnect(); logger.error("--ftp連接失敗--"); System.exit(1); } ftpClient.enterLocalPassiveMode();//這句最好加告訴對面服務器開一個端口
 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ftpClient; }

3.斷開ftp服務方法

    /**
     * 斷開FTP服務器連接
     * @param ftpClient  初始化的對象
     * @throws IOException
     */
    public static void close(FTPClient ftpClient) throws IOException{
        if(ftpClient!=null && ftpClient.isConnected()){
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }

4.下載ftp服務器知道路徑的文件到本地方法

     /**
     * 下載ftp服務器文件方法
     * @param ftpClient FTPClient對象
     * @param newFileName 新文件名
     * @param fileName 原文件(路徑+文件名)
     * @param downUrl  下載路徑
     * @return
     * @throws IOException
     */
    public static boolean downFile(FTPClient ftpClient, String newFileName, String fileName, String downUrl) throws IOException {
        boolean isTrue = false;
        OutputStream os=null;
        File localFile = new File(downUrl + "/" + newFileName);
        if (!localFile.getParentFile().exists()){//文件夾目錄不存在創建目錄
            localFile.getParentFile().mkdirs();
            localFile.createNewFile();
        }
        os = new FileOutputStream(localFile);
        isTrue = ftpClient.retrieveFile(new String(fileName.getBytes(),"ISO-8859-1"), os);
        os.close();
        return isTrue;
    }

5.調用測試main

public static void main(String[] args) throws IOException{
        FTPClient ftpClient = this.ftpConnection("172.*.*.*","*","username","password");boolean flag = downFile(ftpClient,"文件名","/路徑/+文件名","本地路徑");
        close(ftpClients);
        System.out.println(flag );//flag=true說明下載成功
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM