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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
|
@Slf4j
public class FtpUtil implements Closeable {
private final String ftpRootPath;
public FtpUtil(String ftpHost, Integer ftpPort, String ftpRootPath, String ftpUsername, String ftpPasswd) {
this.ftpRootPath = ftpRootPath;
if (ftpClient == null || !ftpClient.isAvailable()) {
ftpClient = new FTPClient();
//设置连接超时时间
ftpClient.setConnectTimeout(1000 * 30);
try {
// 连接FTP服务器
ftpClient.connect(ftpHost, ftpPort);
// 登陆FTP服务器
ftpClient.login(ftpUsername, ftpPasswd);
// 设置文件类型为二进制(如果从FTP下载或上传的文件是压缩文件的时候,不进行该设置可能会导致获取的压缩文件解压失败)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// ftpClient.enterLocalPassiveMode();//开启被动模式,否则文件上传不成功,也不报错
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
log.info("连接FTP失败,用户名或密码错误。");
ftpClient.disconnect();
} else {
log.info("FTP连接成功!");
}
} catch (Exception e) {
log.info("登陆FTP失败,请检查FTP相关配置信息是否正确!" + e);
}
}
}
private static FTPClient ftpClient = null;
/**
* 列出目录下所有文件的完整路径
*
* @param path
* @return {@link InputStream}
* @throws IOException
*/
public String[] listFiles(String path) {
if (ftpClient == null) {
log.error("ftpClient is null!");
return null;
}
FTPFile[] ftpFiles = new FTPFile[0];
try {
ftpFiles = ftpClient.listFiles(path);
} catch (IOException e) {
log.error("获取[ftp:" + path + "]文件列表失败!");
return new String[0];
}
return Arrays.stream(ftpFiles).map(p -> {
if (path.endsWith("/")) {
return path + p.getName();
} else {
return path + "/" + p.getName();
}
}).toArray(String[]::new);
}
/**
* 获取 FTP 文件流
*
* @param path
* @return {@link InputStream}
* @throws IOException
*/
public InputStream getFTPFileInputStream(String path) throws IOException {
if (ftpClient == null) {
log.error("ftpClient is null!");
return null;
}
try {
return ftpClient.retrieveFileStream(path);
} catch (Exception e) {
log.error("读取ftp文件失败!");
return null;
}
}
/**
* 下载文件
*
* @param sourceFilePath 源文件路径
* @param targetDir
* @return {@link String}
*/
public String downloadFile(String sourceFilePath, String targetDir) throws IOException {
if (ftpClient == null) {
log.error("ftpClient is null!");
return null;
}
try (InputStream inputStream = ftpClient.retrieveFileStream(sourceFilePath)) {
String[] split = sourceFilePath.split("/");
if (!targetDir.endsWith("/")) {
targetDir += "/";
}
File file = new File(targetDir);
if (!(file.exists() && file.isDirectory())) {
file.mkdirs();
}
String targetFilePath = targetDir + split[split.length - 1];
try (FileOutputStream outputStream = new FileOutputStream(targetFilePath);) {
byte[] bytes = new byte[10240];
while (inputStream.read(bytes) != -1) {
outputStream.write(bytes);
}
}
return targetFilePath;
} finally {
ftpClient.completePendingCommand();
}
}
/**
* 上传文件
*
* @param sourceFilePath 源文件路径
* @param targetDir
* @return {@link String}
*/
public String uploadFile(String sourceFilePath, String targetFilePath) throws IOException {
if (ftpClient == null) {
log.error("ftpClient is null!");
return null;
}
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFilePath))) {
ftpClient.storeFile(targetFilePath, inputStream);
}
return targetFilePath;
}
public boolean isDirExist(String dir) throws IOException {
return ftpClient.listFiles(dir).length != 0;
}
public boolean mkdir(String dir) throws IOException {
return ftpClient.makeDirectory(dir);
}
/**
* 查找文件夹
*
* @return {@link List}<{@link String}>
* @throws IOException
*/
public String findDir(String dirName) throws IOException {
List<String> paths = new ArrayList<>();
FTPFile[] files = ftpClient.listFiles(ftpRootPath);
for (FTPFile file : files) {
paths.add(ftpRootPath + "/" + file.getName());
}
List<String> childPaths = new ArrayList<>();
for (int i = 0; i < paths.size(); i++) {
String path = paths.get(i);
if (path.contains(dirName)) {
return path;
} else {
files = ftpClient.listFiles(path);
for (FTPFile file : files) {
if (file.isDirectory()) {
if (file.getName().equals(dirName)) {
System.out.println(new String((path + "/" + file.getName()).getBytes(StandardCharsets.ISO_8859_1), "gb2312"));
return path + "/" + file.getName();
}
// 过滤文件夹名称为架次号的
if (file.getName().length() < 15) {
childPaths.add(path + "/" + file.getName());
}
}
}
}
if (i == paths.size() - 1) {
paths.addAll(childPaths);
childPaths.clear();
}
}
return null;
}
@Override
public void close() throws IOException {
if (ftpClient != null) {
try {
ftpClient.disconnect();
} catch (Exception e) {
log.error("ftp 链接关闭失败!");
}
}
}
public static String converToLocalString(String path, String sourceCharset, String targetCharset) {
try {
return new String(path.getBytes(sourceCharset), targetCharset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public boolean completePendingCommand() throws IOException {
return ftpClient.completePendingCommand();
}
public static void main(String[] args) throws IOException {
FtpUtil ftpUtil = new FtpUtil(CentreConfig.FTP_HOST, CentreConfig.FTP_PORT, CentreConfig.FTP_ROOT_PATH, CentreConfig.FTP_USERNAME, CentreConfig.FTP_PASSWD);
// String[] files = ftpUtil.listFiles("/2022/221010CPY8fz113572331/39ffa2c6-4b8a-43a2-8dbb-4e417983baf9/dom/terrain/");
// System.out.println(Arrays.stream(files).collect(Collectors.toList()));
// for (String file : files) {
// String downloadFile = ftpUtil.downloadFile(file, "D:/test/testDom/");
// System.out.println(downloadFile);
// }
}
}
|