Commons net实现 FTP上传下载

最近项目中需要到Ftp文件上传,选择了Commons net。Commons net包中的ftp工具类能够帮助我们轻松实现Ftp方式的文件上传/下载。其中最重要的一个类就是FTPClient类,这个提供了许多FTP操作相关的

方法,比如链接,登录,上传,下载,和注销。

FTP 操作的过程一般为连接服务器,登录,进行文件上传/下载,文件(目录)的添加删除修改等操作。平常用的比较多的是文件的上传和下载。

下面是一些基本的上传操作(将Commons net的jar包引入即可使用):

public class FtpUtil {

    public static void main(String[] args) {

        FTPClient ftpClient = new FTPClient();

        try {
            //连接指定服务器,默认端口为21
            ftpClient.connect("127.0.0.1");

            System.out.println("connect to server");
            //获取响应字符串(FTP服务器上可设置)
            String replyString = ftpClient.getReplyString();
            System.out.println("replyString: " + replyString);
            //获取响应码用于验证是否连接成功
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                System.out.println("");
                System.exit(1);
            }
            //设置链接编码,windows主机UTF-8会乱码,需要使用GBK或gb2312编码
            ftpClient.setControlEncoding("GBK");
            
            //登录服务器
            boolean login = ftpClient.login("luojing", "luojing");
            if (login) {
                System.out.println("登录成功!");
            } else {
                System.out.println("登录失败!");
            }
            
            //获取所有文件和文件夹的名字
            FTPFile[] files = ftpClient.listFiles();
            
            for(FTPFile file : files){
                if(file.isDirectory()){
                    System.out.println(file.getName() + " 是文件夹");
                }
                if(file.isFile()){
                    System.out.println(file.getName() + " 是文件");
                }
            }
            
            //生成InputStream用于上传本地文件
            InputStream in = new FileInputStream("e:\\1.txt");
            
            //上传文件
            ftpClient.storeFile("dest.txt",in);
            in.close();
            
            //注销登录
            boolean logout = ftpClient.logout();
            if (logout) {
                System.out.println("注销成功!");
            } else {
                System.out.println("注销失败!");
            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            //关闭链接需要放在finally语句块中
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}

此外,FTPClient类中也提供了一些文件/文件夹操作的方法。通过commos net提供的方法,可以方便的实现断点传输等功能。我还可以同个retrieveFileStream方法来获取远程服务器中指定文件的一个输入流来供我们手动的进行读操作,也可以使用appendFileStream方法来获取要上传到远程服务器中文件对应的输出流对象,然后我们就可以手动的从本地文件中读取数据然后写入到远程服务中,比如我们想知道上传的进度。总的来说,Commons net提供的方法还是非常好使,非常方便的。一些其他的功能就需要在使用的时候去看API手册了。

可能是环境影响,发现到了公司之后学习效率比在学校高了很多额,继续加油!

原文地址:https://www.cnblogs.com/jdluojing/p/3212412.html