许鹏程
2025-05-19 c356c77683d055f82a668c28db8b56f9c5e04b84
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package com.product.file.service;
 
import com.product.common.lang.StringUtils;
import com.product.core.config.Global;
import com.product.core.exception.BaseException;
import com.product.file.config.FileCode;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
 
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
 
public class FTPService {
    private static Logger logger = Logger.getLogger(FTPService.class);
 
    private FTPClient ftpClient;
 
    private static String ftpServerIp;
    private static Integer ftpServerPort;
    private static String ftpServerUsername;
    private static String ftpServerPassword;
    private static String ftpServerEncode;
 
    private static boolean needUpload2FileServerFlag;
 
    static class Properties {
 
        public Properties() {
        }
 
        public String getProperty(String key) {
            return Global.getSystemConfig(key, null);
        }
    }
 
    static {
        try {
            Properties properties = new Properties();
            needUpload2FileServerFlag = "true".equalsIgnoreCase(properties.getProperty("upload.server"));
            if (needUpload2FileServer()) {
                ftpServerIp = properties.getProperty("ftp.server.ip");
                ftpServerPort = StringUtils.isEmpty(properties.getProperty("ftp.server.port")) ? null : Integer.parseInt(properties.getProperty("ftp.server.port"));
                ftpServerUsername = properties.getProperty("ftp.server.username");
                ftpServerPassword = properties.getProperty("ftp.server.password");
                ftpServerEncode = properties.getProperty("ftp.server.encode");
                if (StringUtils.isEmpty(ftpServerIp)
                        || ftpServerPort == null
                        || StringUtils.isEmpty(ftpServerUsername)
                        || StringUtils.isEmpty(ftpServerPassword)
                        || StringUtils.isEmpty(ftpServerEncode)) {
                    needUpload2FileServerFlag = false;
                } else {
                    needUpload2FileServerFlag = true;
                }
            }
        } catch (BaseException e) {
            logger.info(FileCode.LOAD_FTP_PROPERTIES_FAIL.getText());
            needUpload2FileServerFlag = false;
        }
    }
 
    public FTPService() {
        if (needUpload2FileServerFlag) {
            connectServer();
        }
    }
 
    public static boolean needUpload2FileServer() {
        return needUpload2FileServerFlag;
    }
 
    /**
     * 连接服务
     *
     * @return
     */
    public synchronized boolean connectServer() {
        if (ftpClient != null && ftpClient.isConnected()) {
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                return true;
            }
        }
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding(ftpServerEncode);//解决上传文件时文件名乱码
        int reply = 0;
        try {
            // 连接至服务器
            ftpClient.connect(ftpServerIp, ftpServerPort);
            // 登录服务器
            ftpClient.login(ftpServerUsername, ftpServerPassword);
            //登陆成功,返回码是230
            reply = ftpClient.getReplyCode();
            // 判断返回码是否合法
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return false;
            }
            // 设置以二进制方式传输
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            return true;
        } catch (IOException e) {
            throw new BaseException(FileCode.CONNECT_FTP_SERVER_FAIL.getValue(), FileCode.CONNECT_FTP_SERVER_FAIL.getText(), e);
        }
    }
 
    public boolean fileIsExist(String dir, String fileName) {
        try {
            FTPFile[] ftpFiles = ftpClient.listFiles(dir + "/" + fileName);
            if (ftpFiles != null && ftpFiles.length > 0) {
                for (FTPFile ftpFile : ftpFiles) {
                    if (ftpFile.isFile()) {
                        return true;
                    }
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }
 
    }
 
    /**
     * 断开与远程服务器的连接
     */
    public void closeClient() {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
                ftpClient = null;
            } catch (IOException e) {
                throw new BaseException(FileCode.DISCONNECT_FTP_SERVER_FAIL.getValue(), FileCode.DISCONNECT_FTP_SERVER_FAIL.getText(), e);
            }
        }
    }
 
    /**
     * 上传文件
     *
     * @param inputStream 上传文档的inputStream
     * @param fileName    服务器端文档名
     * @param dir         文件相对目录
     * @return
     */
    public synchronized void uploadFile(InputStream inputStream, String fileName, String dir) {
        try {
            // 创建文件目录
            createDir(dir);
            //设置1M缓冲
            ftpClient.setBufferSize(1024);
            // 设置被动模式
            ftpClient.enterLocalPassiveMode();
            // 上传文件
            ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
        } catch (IOException e) {
            throw new BaseException(FileCode.UPLOAD_FILE_FAIL.getValue(), FileCode.UPLOAD_FILE_FAIL.getText(), e);
        } finally {
            closeClient();
        }
    }
 
    /**
     * 服务器创建目录
     *
     * @param path
     */
    public void createDir(String path) {
        if (StringUtils.isEmpty(path)) {
            return;
        }
        try {
            path = path.replace("\\", ";").replace("/", ";");
            String[] dirArray = path.split(";");
            for (String dirName : dirArray) {
                if (!ftpClient.changeWorkingDirectory(dirName)) {
                    ftpClient.makeDirectory(dirName);
                    ftpClient.changeWorkingDirectory(dirName);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new BaseException(FileCode.UPLOAD_FILE_FAIL.getValue(), FileCode.UPLOAD_FILE_FAIL.getText(), e);
        }
    }
 
    /**
     * 下载指定文件到本地指定目录
     *
     * @param ftpPath  FTP服务器上的相对路径,例如:test/123.txt
     * @param savePath 保存文件到本地的路径,例如:D:/test
     * @return 成功返回true,否则返回false
     */
    public boolean downloadFile(String ftpPath, String savePath) {
        if (ftpClient != null) {
            try {
                // 设置被动模式,开通一个端口来传输数据
                ftpClient.enterLocalPassiveMode();
                String[] fileNames = ftpClient.listNames(ftpPath);
                if (fileNames == null || fileNames.length == 0) {
                    logger.error(FileCode.SERVER_NO_FILE.getText());
                    return Boolean.FALSE;
                }
 
                File file = new File(savePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
                OutputStream os = new FileOutputStream(file);
                ftpClient.retrieveFile(ftpPath, os);
                os.flush();
                os.close();
            } catch (IOException e) {
                logger.error("下载文件失败", e);
                return false;
            } finally {
                closeClient();
            }
        }
        return Boolean.TRUE;
    }
 
    /**
     * 下载指定文件到本地指定目录
     *
     * @param ftpPath FTP服务器上的相对路径,例如:test/123.txt
     * @param os      文件输出流
     * @return 成功返回true,否则返回false
     */
    public boolean downloadFile(String ftpPath, OutputStream os) {
        if (ftpClient != null) {
            try {
                // 设置被动模式,开通一个端口来传输数据
                ftpClient.enterLocalPassiveMode();
                String[] fileNames = ftpClient.listNames(ftpPath);
                if (fileNames == null || fileNames.length == 0) {
                    logger.error(FileCode.SERVER_NO_FILE.getText());
                    return Boolean.FALSE;
                }
 
                ftpClient.retrieveFile(ftpPath, os);
                os.flush();
            } catch (IOException e) {
                logger.error("下载文件失败", e);
                return false;
            } finally {
                closeClient();
            }
        }
        return Boolean.TRUE;
    }
 
    /**
     * 下载该目录下所有文件
     *
     * @param ftpPathList
     * @param os
     * @return 成功返回true,否则返回false
     */
    public boolean downloadFiles(List<String> ftpPathList, OutputStream os) {
        if (ftpClient != null) {
            try {
                ZipOutputStream out = new ZipOutputStream(os);
 
                // 设置被动模式,开通一个端口来传输数据
                ftpClient.enterLocalPassiveMode();
                for (String ftpPath : ftpPathList) {
                    String[] fileNames = ftpClient.listNames(ftpPath);
                    if (fileNames == null || fileNames.length == 0) {
                        logger.error("服务端文件不存在");
                        return Boolean.FALSE;
                    }
                    out.putNextEntry(new ZipEntry(fileNames[0]));
                    ftpClient.retrieveFile(ftpPath, out);
                    out.flush();
                    out.closeEntry();
                }
                out.flush();
                out.close();
            } catch (IOException e) {
                logger.error("下载文件失败", e);
            } finally {
                closeClient();
            }
        }
        return Boolean.TRUE;
    }
 
    /**
     * 删除ftp文件
     *
     * @param pathname
     * @param filename
     * @return
     */
    public synchronized boolean deleteFile(String pathname, String filename) {
        connectServer();
        boolean flag = false;
        try {
            System.out.println("开始删除文件");
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.dele(filename);
            ftpClient.logout();
            flag = true;
            System.out.println("删除文件成功");
        } catch (Exception e) {
            System.out.println("删除文件失败");
            e.printStackTrace();
        } finally {
            closeClient();
        }
        return flag;
    }
}