FTP java开发

xiaoxiao2021-02-27  185

方法简介 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")) 类容查考至网络,通过自己实践得来,不喜勿喷

转载请注明原文地址: https://www.6miu.com/read-13882.html

最新回复(0)