import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketException; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.lang.StringUtils; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPReply; import org.apache.commons.net.ftp.FTPSClient; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; @Slf4j @Component public class FtpsUtil { private FTPSClient ftpClient = new FTPSClient(); private FileOutputStream fos = null; boolean ckmcaCheck = false; boolean custChck = false; boolean connCheck = false; String odsPath = null; /** * 连接 */ public boolean connect(String host, int port, String username, String password) { try { log.info("开始连接..."); log.info("[username]" + username + "[host]" + host + "[port]" + port + "[password]" + password); // 连接 this.ftpClient.connect(host, port); int reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.info("连接失败,请检查用户名和密码"); this.ftpClient.disconnect(); return false; } // 登录 log.info("开始登录!"); this.ftpClient.login(username, password); this.ftpClient.setBufferSize(1024 * 30); this.ftpClient.setDataTimeout(600000); this.ftpClient.setControlKeepAliveReplyTimeout(12000); this.ftpClient.setControlKeepAliveTimeout(1200); this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE); this.ftpClient.execPROT("P"); this.ftpClient.execPBSZ(0); this.ftpClient.enterLocalPassiveMode(); // 设置被动模式去传输 this.ftpClient.setUseEPSVwithIPv4(true); this.ftpClient.setControlEncoding("utf8"); log.info("登录成功!"); return true; } catch (SocketException e) { log.info("连接失败!" + e); return false; } catch (Exception e) { log.info("下载失败!" + e); return false; } } /** * 获取当前日期的前一天 yyyyMMdd */ public static String dayBefore() { SimpleDateFormat dft = new SimpleDateFormat("yyyMMdd"); Date now = new Date(); Calendar date = Calendar.getInstance(); date.setTime(now); date.set(Calendar.DATE, date.get(Calendar.DATE) - 1); String daybefor = ""; try { daybefor = dft.format(date.getTime()); } catch (Exception e) { e.printStackTrace(); } return daybefor; } private boolean downFileOrDirNoClose(String ftpFileName, String localDir,String todayDate) { boolean flag = false; String ckmcaCheckPath = "q1_"+todayDate+"_end"; String custCheckPath = "2q_"+todayDate+"_end"; String connCheckPath = "q3_"+todayDate+"_end"; try { // 目标文件 File temp = new File(localDir); if (!temp.exists()) { temp.mkdirs(); } ftpClient.enterLocalPassiveMode(); log.info("读取路径:"+ftpFileName); String[] names = ftpClient.listNames(); log.info("读取路径下文件数量:"+names.length); for (int i = 0; i < names.length; i++) { String fileName = names[i]; if (todayDate.equals(fileName) || fileName.contains("q1") || fileName.contains("q2") || fileName.contains("q3")) { if (isDir(fileName)) { downFileOrDirNoClose(ftpFileName + File.separator + fileName, localDir + File.separator + fileName,todayDate); ftpClient.changeToParentDirectory(); } else { if (ckmcaCheckPath.equals(fileName)){ ckmcaCheck = true; }else if (connCheckPath.equals(fileName)){ connCheck = true; }else if (custCheckPath.equals(fileName)){ custChck = true; } } } } if (odsPath.equals(ftpFileName)){ if (ckmcaCheck){ String fileName = "q1"+todayDate+".txt"; File localfile = new File(localDir+ File.separator + fileName); if (!localfile.exists()) { fos = new FileOutputStream(localfile); ftpClient.retrieveFile(fileName, fos); } else { // 文件已存在,先进行删除 log.debug("开始删除已存在文件:{}",localfile); fos = new FileOutputStream(localfile); ftpClient.retrieveFile(ftpFileName, fos); } log.info("下载文件名称为:{},文件存在地址为:{}", fileName, localfile); ckmcaCheck = false; }else{ log.info("不存在:"+ckmcaCheckPath); } if (connCheck){ String fileName = "q2"+todayDate+".txt"; File localfile = new File(localDir+ File.separator + fileName); if (!localfile.exists()) { fos = new FileOutputStream(localfile); ftpClient.retrieveFile(fileName, fos); } else { // 文件已存在,先进行删除 log.debug("开始删除已存在文件:"+localDir); fos = new FileOutputStream(localfile); ftpClient.retrieveFile(ftpFileName, fos); } log.info("下载文件名称为:{},文件存在地址为:{}", fileName, localfile); connCheck = false; }else{ log.info("不存在:"+connCheckPath); } if (custChck){ String fileName = "q3"+todayDate+".txt"; File localfile = new File(localDir+ File.separator + fileName); if (!localfile.exists()) { fos = new FileOutputStream(localfile); ftpClient.retrieveFile(fileName, fos); } else { log.debug("开始删除已存在文件"+localDir); fos = new FileOutputStream(localfile); ftpClient.retrieveFile(ftpFileName, fos); } log.info("下载文件名称为:{},文件存在地址为:{}", fileName, localfile); custChck = false; }else{ log.info("不存在:"+custCheckPath); } } flag = true; } catch (SocketException e) { log.info("连接失败!" + e); } catch (Exception e) { log.info("下载失败!" + e); } return flag; } /** * 手动关闭连接 */ public void closeFtpClient() { try { ftpClient.logout(); } catch (IOException e) { log.info("ftpClient.logout()执行失败" + e); } close(fos); } /** * 关闭连接及输出流 * * @param fos */ private void close(FileOutputStream fos) { try { if (fos != null) { fos.close(); } log.info("退出登录"); if (this.ftpClient != null) { try { ftpClient.disconnect(); ftpClient = null; } catch (IOException ioe) { log.info("ftpClient.disconnect()执行失败", ioe); } } log.info("关闭连接"); } catch (IOException e) { log.info("关闭连接失败" + e); } } public boolean downloadFile(String ftpFileName, String localDir,String todayDate, String host, int port, String username, String password) { boolean loginFlag = connect(host, port, username, password); boolean flag = false; if (loginFlag) { odsPath = ftpFileName+File.separator+todayDate; flag = downFileOrDirNoClose(ftpFileName, localDir,todayDate); odsPath = null; } return flag; } /** * 判断是否是目录 * * @param fileName * @return */ public boolean isDir(String fileName) { boolean flag = false; try { // 切换目录,若当前是目录则返回true,否则返回false。 flag = ftpClient.changeWorkingDirectory(fileName); } catch (Exception e) { log.info("判断目录失败" + e); } return flag; } /** * @param strRemotePath 上传目录 * @param strLocalPath 上传文件在达飞的地址 * @param remoteFileName 上传后的命名 * @return */ public boolean uploadFile(String strRemotePath, String strLocalPath, String remoteFileName, String host, int port, String username, String password) { if (!this.ftpClient.isConnected()) { connect(host, port, username, password); } boolean flag = false; if (this.ftpClient.isConnected()) { File file = new File(strLocalPath); InputStream input = null; try { input = new FileInputStream(file); if (!ftpClient.changeWorkingDirectory(strRemotePath)) { // 如果目录不存在创建目录 String[] dirs = strRemotePath.split("/"); String tempPath = ""; for (String dir : dirs) { if (null == dir || "".equals(dir)) { continue; } tempPath += "/" + dir; if (!ftpClient.changeWorkingDirectory(tempPath)) { if (!ftpClient.makeDirectory(tempPath)) { log.info("创建远程目录失败"); } else { ftpClient.changeWorkingDirectory(tempPath); } } } } flag = this.ftpClient.storeFile(remoteFileName, input); } catch (Exception e) { log.info("文件上传失败"); } finally { if (input != null) { try { input.close(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } return flag; } /** * 下载 * * @param strUrlPath * @param strLocalPath * @param strFolderPath * @return */ public boolean downloadFile(String strUrlPath, String strLocalPath, String strFolderPath) { boolean result = true; GetMethod httpGet = new GetMethod(strUrlPath); if (!"".equals(strFolderPath)) { File folder = new File(strFolderPath); if (!folder.exists()) { System.out.println(folder.mkdirs()); } } InputStream in = null; FileOutputStream out = null; try { HttpClient httpClient = new HttpClient(); httpClient.executeMethod(httpGet); in = httpGet.getResponseBodyAsStream(); out = new FileOutputStream(new File(strLocalPath)); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b)) != -1) { out.write(b, 0, len); } in.close(); out.close(); } catch (Exception e) { log.info("httpClient下载文件失败" + e); result = false; } finally { httpGet.releaseConnection(); try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e1) { log.info("文件流信息关闭失败" + e1); result = false; } } log.info("####下载文件成功:" + strUrlPath); return result; } }
看不明白请私信我,或者留言