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 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; } }