文章首发于:clawhub.club
java使用ftp是没有提供创建多级文件夹的能力的,所以只能自己封装实现:
这里引用了commons-net Maven依赖:
1 2 3 4 5 6 7
| <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency>
|
创建多级目录
FTP远程进入多层目录文件,如果已存在该目录文件,则不创建,如果无,则循环创建多层目录文件,具体源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
private static void changeAndCreateDirectoryIfInExist(FTPClient ftpClient, String remote) throws IOException { if (ftpClient.changeWorkingDirectory(remote)) { return; } String[] paths = remote.split(File.separator); for (String path : paths) { if (ftpClient.changeWorkingDirectory(remote)) { continue; } if (ftpClient.makeDirectory(path)) { ftpClient.changeWorkingDirectory(path); } } }
|
也贴上获取FTPClient和上传文件的源码:
获取FTPClient
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
private static final String ACTIVE = "active";
public static FTPClient getFTPClient(String ftpIp, int ftpPort, String ftpMode, String ftpUsername, String ftpPassword) { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(ftpIp, ftpPort); ftpClient.login(ftpUsername, ftpPassword); ftpClient.changeWorkingDirectory("/"); ftpClient.setRemoteVerificationEnabled(false); if (ACTIVE.equalsIgnoreCase(ftpMode)) { ftpClient.enterLocalActiveMode(); } else { ftpClient.enterLocalPassiveMode(); } } catch (IOException e) { throw new RuntimeException("获取FTP客户端出错!", e); } return ftpClient; }
|
上传文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
private static final int BUFFER_SIZE = 1024;
public static String uploadFile(FTPClient ftpClient, Path localPath, String remotePath, String targetFileName) { String statusCode; InputStream fis = null; try { fis = new ByteArrayInputStream(Files.readAllBytes(localPath)); changeAndCreateDirectoryIfInExist(ftpClient, remotePath); ftpClient.setBufferSize(BUFFER_SIZE); ftpClient.setControlEncoding("UTF-8"); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.storeFile(targetFileName, fis); statusCode = ftpClient.getStatus(); } catch (IOException e) { throw new RuntimeException("FTP客户端出错!", e); } finally { if (null != fis) { ftpClose(ftpClient, fis); } } return statusCode;
}
private static void ftpClose(FTPClient ftpClient, InputStream fis) { try { fis.close(); if (null != ftpClient && ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException e) { throw new RuntimeException("关闭FTP客户端出错!", e); }
}
|
如果代码有问题,欢迎评论交流。