1. 程式人生 > >Java Ftp客戶端

Java Ftp客戶端

1.第三方庫commons-net-*.jar

開啟Download Apache Commons Net下載jar包

2.上傳檔案

private boolean upload(String absolutePath, String name) {
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(serverIP);
        ftpClient.login(USERNAME, PASSWORD);

        int reply = ftpClient.getReplyCode();
        System.out.println("reply = " + reply);
        if (FTPReply.isPositiveCompletion(reply)) {
            // 設定檔案型別
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();

            InputStream input = new FileInputStream(absolutePath);
            boolean result = ftpClient.storeFile(name, input);
            System.out.println("result = " + result);
            input.close();
            ftpClient.logout();

            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return false;
}

3.下載檔案

private boolean download(String remotePath, String localPath) {
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(serverIP);
        ftpClient.login(USERNAME, PASSWORD);

        int reply = ftpClient.getReplyCode();
        System.out.println("reply = " + reply);
        if (FTPReply.isPositiveCompletion(reply)) {
            OutputStream output = new FileOutputStream(localPath);				
            boolean result = ftpClient.retrieveFile(remotePath, output);
            System.out.println("result = " + result);
            output.close();
            ftpClient.logout();

            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return false;
}

相關文章
Java Ftp客戶端
Windows下搭建Ftp伺服器
Java Telnet客戶端
Windows下搭建Telnet伺服器