apache FTP
Posted wangfb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了apache FTP相关的知识,希望对你有一定的参考价值。
1.maven依赖
<dependencies> <!--FtpClient所在的包--> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency> <!--日志--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.2</version> </dependency> <!--单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> </dependencies>
2.文件上传(多级目录)
public static void main(String[] args) throws IOException { // uploadFile(); FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("UTF-8"); ftpClient.connect("192.168.10.200",21); ftpClient.login("root", "123456"); String path="aa/bb1/cc1"; String fileName="1.png"; InputStream in = new FileInputStream("d://1.png"); uploadFile(ftpClient, path, in); } private static void uploadFile(FTPClient ftpClient, String path, InputStream in) throws IOException { int replyCode = ftpClient.getReplyCode(); ftpClient.setDataTimeout(120000); //设置为二进制文件 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(replyCode)) { ftpClient.disconnect(); System.out.println("FTP连接失败"); }else { System.out.println("FTP连接成功"); } boolean changeWorkingDirectory = ftpClient.changeWorkingDirectory(path); //文件夹切换失败,则创建文件夹 if(!changeWorkingDirectory){ String[] split = path.split("/"); for (String s : split) { if (ftpClient.changeWorkingDirectory(s)) { continue; } boolean makeDirectory = ftpClient.makeDirectory(s); if (makeDirectory) { boolean b = ftpClient.changeWorkingDirectory(s); if(!b){ throw new RuntimeException("切换目录失败"); } } } } String removePath = new String("1.png".getBytes("UTF-8"),"iso-8859-1"); //上传 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); if(ftpClient.storeFile(removePath, in)){ System.out.println("文件上传成功"); }else{ System.out.println("文件上传失败"); } //关闭文件流 in.close(); //关闭连接 if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); } }
3.下载单个文件
public static void downLoadFile(FTPClient ftpClient, String remoteFile) throws IOException { int replyCode = ftpClient.getReplyCode(); ftpClient.setDataTimeout(120000); //设置为二进制文件 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(replyCode)) { ftpClient.disconnect(); System.out.println("FTP连接失败"); } else { System.out.println("FTP连接成功"); } // 同理,假如指定不存在的路径,会去根路径下查找 ftpClient.changeWorkingDirectory("test2"); File file = new File("d://11.png"); FileOutputStream fos = new FileOutputStream(file); boolean result = ftpClient.retrieveFile(remoteFile, fos); if (result) { System.out.println("下载成功!"); } else { System.out.println("下载失败!"); } //关闭文件流 fos.flush(); fos.close(); //关闭连接 if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); } }
以上是关于apache FTP的主要内容,如果未能解决你的问题,请参考以下文章
maven中,POM.XML中怎么配置org.apache.commons.net.ftp引用包,求配置代码- -