FTP java开发

方法简介
1
	FTPClient client = new FTPClient();
2
	client.connect("ftp.host.com", port);
3
	client.login("carlo", "mypassword");
4
	client.createDirectory("newfolder");
5
	client.disconnect(true);
示例如下:

 先来写一登录示例,然后根据此分别来说各种操作的示例代码:
    package test;  
    import it.sauronsoftware.ftp4j.FTPClient;  
    /** 
     * FTP操作测试 
     * @说明  
     * @author cuisuqiang 
     * @version 1.0 
     * @since 
     */  
    public class Ftp4jTest {  
        public static void main(String[] args) {  
            try {  
                // 创建客户端  
                FTPClient client = new FTPClient();  
                // 不指定端口,则使用默认端口21  
                client.connect("192.168.1.122", 21);  
                // 用户登录  
                client.login("123", "123123");  
                // 打印地址信息  
                System.out.println(client);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
    }  
登录进行退出操作:
    // 安全退出  
     client.disconnect(true);  
    // 强制退出  
    client.disconnect(false);  
获得当前文件夹路径:
    // 当前文件夹  
    String dir = client.currentDirectory();  
    System.out.println(dir);  
创建目录
    // 创建目录  
    client.createDirectory("123");  
切换文件夹路径,可以使用绝对路径或者是相对路径,相对路径就是相对与当前所在的路径:
    // 改变当前文件夹 绝对路径  
    // client.changeDirectory(dir + "/123");  
    //  改变当前文件夹 相对路径  
    client.changeDirectory("123");  
    // 当前文件夹  
    dir = client.currentDirectory();  
    System.out.println(dir);  
 返回上级目录
    client.changeDirectoryUp();  
    // 重新获得 当前文件夹  
    dir = client.currentDirectory();  
    System.out.println(dir);  
重命名文件或文件夹
    client.rename("123", "456");  
删除目录(不能删除非空目录)  绝对或相对路径
    client.deleteDirectory("456");  
移动文件或文件夹
    client.rename("readme.txt", dir + "/456/readme.txt");  
删除文件
    client.deleteFile(dir + "/456/readme.txt");  
罗列当前目录下的文件和文件的修改日期,注意不要操作 . 和 .. 文件
    // 浏览文件  
    FTPFile[] list = client.list();  
    // 使用通配浏览文件  
    // FTPFile[] list = client.list("*.txt");  
    // 显示文件或文件夹的修改时间 你不能获得 . 或 .. 的修改日期,否则Permission denied  
    for(FTPFile f : list){  
        if(!f.getName().equals(".") && !f.getName().equals("..")){  
            System.out.print(f.getName() + "\t");  
            System.out.println(client.modifiedDate(f.getName()));  
        }  
    }  
下载文件
    File file = new File("C:\\localFile.txt");  
    client.download("remoteFile.txt", file);  
上传文件到当前目录
    client.upload(file);  
监听文件传输状态
创建一个实现FTPDataTransferListener接口的类:
    /** 
     * 监听文件传输的状态,上传下载时最后一个参数 
     * @说明  
     * @author cuisuqiang 
     * @version 1.0 
     * @since 
     */  
    class MyTransferListener implements      {  
      
        // 文件开始上传或下载时触发  
        public void started() {  
            System.out.println("started");  
        }  
        // 显示已经传输的字节数  
        public void transferred(int length) {  
            System.out.println(length);  
        }  
        // 文件传输完成时,触发  
        public void completed() {  
            System.out.println("completed");  
        }  
        // 传输放弃时触发  
        public void aborted() {  
            System.out.println("aborted");  
        }  
        // 传输失败时触发  
        public void failed() {  
            System.out.println("failed");  
        }  
    }  
然后在上传或下载时增加一个参数即可,例如上传时:
    client.upload(file, new MyTransferListener());  


1. 依赖库

 ftp4j-1.5.jar

2. 共用方法

   上传下载方法需要引用的方法:

public static URL newURL(URL parentUrl, String child)throws MalformedURLException {
        String path = parentUrl.getPath();
        if(!path.endsWith("/")){
            path += "/";
        }
        path += child;
        return new URL(parentUrl, path);
    }

3. 下载文件

public static void download(URL url, String username, String password, File file){
        download(url, username, password, "UTF-8", file);
    }
    public static void download(URL url, String username, String password, String encoding, File file){
        FTPClient client = new FTPClient();
        client.setCharset(encoding);
        client.setType(FTPClient.TYPE_BINARY); 
        //连接到指定的FTP服务器(域名或IP) 不指定端口,则使用默认端口21
        try {
            int port = url.getPort();
            if(port < 1){
                port = 21;
            }
            client.connect(url.getHost(), port);
            //登录验证
            client.login(username, password);
//            client.changeDirectory(url.getPath());
            client.download(url.getFile(), file);
            client.logout();
            //安全退出
            client.disconnect(true);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    }

4. 下载文件夹

public static void downloadFolder(URL url, String username, String password, File folder){
        downloadFolder(url, username, password, "UTF-8", folder);
    }
    public static void downloadFolder(URL url, String username, String password, String encoding, File folder){
        FTPClient client = new FTPClient();
        client.setCharset(encoding);
        client.setType(FTPClient.TYPE_BINARY); 
        //连接到指定的FTP服务器(域名或IP) 不指定端口,则使用默认端口21
        try {
            int port = url.getPort();
            if(port < 1){
                port = 21;
            }
            client.connect(url.getHost(), port);
            //登录验证
            client.login(username, password);
            downloadFolder(client, url, folder);
            client.logout();
            //安全退出
            client.disconnect(true);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    }
    private static void downloadFolder(FTPClient client, URL url, File folder)throws Exception{
        client.changeDirectory(url.getPath());
        FTPFile[] ftpFiles = client.list();
        if(!folder.exists()){
            folder.mkdirs();
        }
        for(FTPFile ftpFile : ftpFiles){
            String name = ftpFile.getName();
            if(ftpFile.getType() == FTPFile.TYPE_FILE){
                client.changeDirectory(url.getPath());
                File f = new File(folder, name);
                client.download(name, f);
            }else if(ftpFile.getType() == FTPFile.TYPE_DIRECTORY){
                downloadFolder(client, newURL(url, name), new File(folder, name));
            }
        }
    }

5. 上传文件

public static void upload(URL url, String username, String password, File file){
        upload(url, username, password, "UTF-8", file);
    }
    public static void upload(URL url, String username, String password, String encoding, File file){
        FTPClient client = new FTPClient();
        client.setCharset(encoding);
        client.setType(FTPClient.TYPE_BINARY); 
        //连接到指定的FTP服务器(域名或IP) 不指定端口,则使用默认端口21
        try {
            int port = url.getPort();
            if(port < 1){
                port = 21;
            }
            client.connect(url.getHost(), port);
            //登录验证
            client.login(username, password);
            client.changeDirectory(url.getPath());
            client.upload(file);
            client.logout();
            //安全退出
            client.disconnect(true);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    }

6. 上传文件夹

public static void uploadFolder(URL url, String username, String password, File folder){
        uploadFolder(url, username, password, "UTF-8", folder);
    }
    public static void uploadFolder(URL url, String username, String password, String encoding, File folder){
        FTPClient client = new FTPClient();
        client.setCharset(encoding);
        client.setType(FTPClient.TYPE_BINARY); 
        //连接到指定的FTP服务器(域名或IP) 不指定端口,则使用默认端口21
        try {
            int port = url.getPort();
            if(port < 1){
                port = 21;
            }
            client.connect(url.getHost(), port);
            //登录验证
            client.login(username, password);
            client.changeDirectory(url.getPath());
            String[] files = folder.list();
            for(String file : files){
                File f = new File(folder, file);
                if(f.isDirectory()){
                    uploadFolder(client, url, f);
                }else{
                    client.changeDirectory(url.getPath());
                    client.upload(f);
                }
            }
            client.logout();
            //安全退出
            client.disconnect(true);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    }
    private static void uploadFolder(FTPClient client, URL parentUrl, File folder)throws Exception{
        client.changeDirectory(parentUrl.getPath());
        if(!existsFtpDir(client, folder.getName())){
            client.createDirectory(folder.getName());
        }
        client.changeDirectory(folder.getName());
        
        String[] fileList = folder.list();
        if(fileList == null){
            return ;
        }
        
        for(String file : fileList){
            File f = new File(folder, file);
            if(f.isDirectory()){
                uploadFolder(client, newURL(parentUrl, folder.getName()), f);
            }else if(f.isFile()){
                client.changeDirectory(parentUrl.getPath());
                client.changeDirectory(folder.getName());
                client.upload(f);
            }
        }
    }
    
    private static boolean existsFtpDir(FTPClient client, String dir)throws Exception{
        FTPFile[] ftpFiles = client.list();
        for(FTPFile ftpFile : ftpFiles){
            if((ftpFile.getType() == FTPFile.TYPE_DIRECTORY) && (dir.equals(ftpFile.getName()))){
                return true;
            }
        }
        return false;
    }

7. 判断是否存在文件或文件夹

public static boolean exists(URL url, String username, String password){
        return exists(url, username, password, "UTF-8");
        
    }
    public static boolean exists(URL url, String username, String password, String encoding){
        FTPClient client = new FTPClient();
        client.setCharset(encoding);
        client.setType(FTPClient.TYPE_BINARY);
        try {
            int port = url.getPort();
            if(port < 1){
                port = 21;
            }
            String[] welcome = client.connect(url.getHost(), port);
            logger.info("welcome = " + welcome.length);
            //登录验证
            client.login(username, password);
            String path = url.getPath();
            logger.info("path = " + path);
            if(path.indexOf(".") != -1){//文件
                int index = path.lastIndexOf("/");
                String p = path.substring(0, index);
                String f = path.substring(index + 1);
                logger.info("p = " + p + ", f = " + f);
                client.changeDirectory(p);
                FTPFile[] ftpFiles = client.list();
                for(FTPFile ftpFile : ftpFiles){
                    if((ftpFile.getType() == FTPFile.TYPE_FILE) && (ftpFile.getName().equals(f))){
                        return true;
                    }
                }
                return false;
            }else{//文件夹
                client.changeDirectory(path);
            }
            client.logout();
            //安全退出
            client.disconnect(true);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
            return false;
        }
        
        return true;
    }

8. FTP服务器之间复制文件夹

public static void copyFolder(URL sourceUrl, String sourceUsername, String sourcePassword, String sourceEncoding, URL destUrl, String destUsername, String destPassword, String destEncoding, String tmpDir)throws IOException{
        downloadFolder(sourceUrl, sourceUsername, sourcePassword, sourceEncoding, new File(tmpDir));
        uploadFolder(destUrl, destUsername, destPassword, destEncoding, new File(tmpDir));
        FileUtil.deleteFolder(tmpDir);
    }
    public static void copyFolder(URL sourceUrl, String sourceUsername, String sourcePassword, URL destUrl, String destUsername, String destPassword, String tmpDir)throws IOException{
        copyFolder(sourceUrl, sourceUsername, sourcePassword, "UTF-8", destUrl, destUsername, destPassword, "UTF-8", tmpDir);
    }

9.删除文件

public static void delete(URL url, String username, String password){
        delete(url, username, password, "UTF-8");
    }
    public static void delete(URL url, String username, String password, String encoding){
        FTPClient client = new FTPClient();
        client.setCharset(encoding);
        client.setType(FTPClient.TYPE_BINARY); 
        //连接到指定的FTP服务器(域名或IP) 不指定端口,则使用默认端口21
        try {
            int port = url.getPort();
            if(port < 1){
                port = 21;
            }
            client.connect(url.getHost(), port);
            //登录验证
            client.login(username, password);
            client.deleteFile(url.getPath());
            client.logout();
            //安全退出
            client.disconnect(true);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    }

 

10. 简单用法

uploadFolder(new URL("ftp://localhost:21/test/"), "admin", "123", new File("d:/test"));
downloadFolder(new URL("ftp://localhost:21/test/"), "admin", "123", new File("d:/dbtest"))

类容查考至网络,通过自己实践得来,不喜勿喷

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ftp4j是一个FTP客户端Java类库,实现了FTP客户端应具有的大部分功能。可以将ftp4j嵌到你的Java应用中,来传输文件(包括上传和下载),浏览远程FTP服务器上的目录和文件,创建、删除、重命,移动远程目录和文件。ftp4j提供多种方式连接到远程FTP服务器包括:通过 TCP/IP直接连接,通过FTP代理、HTTP代理、SOCKS4/4a代理和SOCKS5代理连接,通过SSL安全连接。 简单应用---API介绍 The main class of the library is FTPClient (it.sauronsoftware.ftp4j.FTPClient). 1. 创建FTPClient实例 FTPClient client = new FTPClient(); 连接到指定的FTP服务器(域名或IP) 不指定端口,则使用默认端口21 client.connect("ftp.host.com", /*21*/); 登录验证 client.login("user", "pswd"); 下面是匿名登录 //client.login("anonymous", "密码任意设置"); client.login("anonymous", "ftp4j"); 安全退出 client.disconnect(true); //强制退出 //client.disconnect(false); 文件以及文件夹操作: 取得当前文件夹 String dir = client.currentDirectory(); 改变当前文件夹 client.changeDirectory(newPath); //绝对路径 //client.changeDirectory("/an/absolute/one"); //相对路径 //client.changeDirectory("relative"); //回退到上级目录 client.changeDirectoryUp(); //重命名文件或文件夹 client.rename("oldname", "newname"); //移动文件或文件夹 client.rename("myfile.txt", "myfolder/myfile.txt"); //删除文件 client.deleteFile(relativeOrAbsolutePath); //client.deleteFile("useless.txt"); //创建目录 client.createDirectory("newfolder"); //删除目录(空目录) client.deleteDirectory(absoluteOrRelativePath); //client.deleteDirectory("oldfolder"); //浏览文件 FTPFile[] list = client.list(); //使用通配浏览文件 FTPFile[] list = client.list("*.jpg"); //显示文件或文件夹的修改时间 java.util.Date md = client.modifiedDate("filename.ext"); //上传和下载文件 //下载服务器上remoteFile.ext 下载到本地 localFile.ext client.download("remoteFile.ext", new java.io.File("localFile.ext")); //上传 本地 localFile.ext 到当前目录 client.upload(new java.io.File("localFile.ext")); // 上传和下载文件时, 监听文件传输的状态 public class MyTransferListener implements FTPDataTransferListener { //文件开始上传或下载时触发 public void started() { } //显示已经传输的字节数 public void transferred(int length) { } //文件传输完成时,触发 public void completed() { } //传输放弃时触发 public void aborted() { // Transfer aborted } //传输失败时触发 public void failed() { } 示例: client.download("remoteFile.ext", new java.io.File("localFile.ext"), new MyTransferListener()); client.upload(new java.io.File("localFile.ext"), new MyTransferListener()); //ftp4j也支持断点续传功能 下面是一个简单示例:*参数 1056 跳过 1056字节点下载 client.download("remoteFile.ext", new java.io.File("localFile.ext"), 1056); 设置传输模式 //ASC码 client.setType(FTPClient.TYPE_TEXTUAL); //二进制 client.setType(FTPClient.TYPE_BINARY); //自动选择(根据文件内容) client.setType(FTPClient.TYPE_AUTO); //设置连接器 client.setConnector(connector); SSL 套接字连接 client.setConnector(it.sauronsoftware.ftp4j.connectors.SSLConnector) client.setConnector(anyConnectorYouWant);

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值