Java Ftp客户端

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chennai1101/article/details/84789043

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服务器

猜你喜欢

转载自blog.csdn.net/chennai1101/article/details/84789043