package com.wbr.app.read.ftp;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.SocketException;import java.net.URLEncoder;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;/** * * - 链接 FTP 上传下载 工具类 * * @author panpan.wang * @version 1.0 (2018年3月13日 ) */public class FtpUtil { private static Logger logger = Logger.getLogger(FtpUtil.class); /** * 获取FTPClient对象 * * @param ftpHost * FTP主机服务器 * @param ftpPassword * FTP 登录密码 * @param ftpUserName * FTP登录用户名 * @param ftpPort * FTP端口 默认为21 * @return */ public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) { FTPClient ftpClient = new FTPClient(); try { ftpClient = new FTPClient(); ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器 ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器 if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { logger.info("未连接到FTP,用户名或密码错误。"); ftpClient.disconnect(); } else { logger.info("FTP连接成功。"); } } catch (SocketException e) { e.printStackTrace(); logger.info("FTP的IP地址可能错误,请正确配置。"); } catch (IOException e) { e.printStackTrace(); logger.info("FTP的端口错误,请正确配置。"); } return ftpClient; } /** * 下载 FTP服务器上文件夹下的所有文件到指定的本地路径下 * * @param ftpHost * @param ftpUserName * @param ftpPassword * @param ftpPort * @param ftpPath * @param localPath * @return */ public static void downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String localPath) { FTPClient ftpClient = null; try { ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); ftpClient.setControlEncoding("UTF-8"); // 中文支持 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(ftpPath); FTPFile[] files = ftpClient.listFiles(ftpPath); for (FTPFile ftpFile : files) { File localFile = new File(localPath + File.separatorChar + ftpFile.getName()); OutputStream os = new FileOutputStream(localFile); ftpClient.retrieveFile(ftpFile.getName(), os); os.close(); } ftpClient.logout(); } catch (FileNotFoundException e) { logger.info("没有找到" + ftpPath + "文件"); e.printStackTrace(); } catch (SocketException e) { logger.info("连接FTP失败."); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); logger.info("文件读取错误。"); e.printStackTrace(); } } /** * Description: 向FTP服务器上传文件 * * @param ftpHost * FTP服务器hostname * @param ftpUserName * 账号 * @param ftpPassword * 密码 * @param ftpPort * 端口 * @param ftpPath * FTP服务器中文件所在路径 格式: ftptest/aa * @param fileName * ftp文件名称 * @param input * 文件流 * @return 成功返回true,否则返回false */ public static boolean uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String fileName, InputStream input) { boolean success = false; FTPClient ftpClient = null; try { int reply; ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); return success; } ftpClient.setControlEncoding("UTF-8"); // 中文支持 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(ftpPath); ftpClient.storeFile(fileName, input); input.close(); ftpClient.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { } } } return success; } /** * * 删除ftp上的文件 * * @return true || false */ @SuppressWarnings("unused") public boolean removeFile(String srcFname) { FTPClient ftpClient = null; boolean flag = false; if (ftpClient != null) { try { flag = ftpClient.deleteFile(srcFname); } catch (IOException e) { e.printStackTrace(); this.closeCon(); } } return flag; }// end method removeFile /** * 销毁ftp连接 * * @author */ @SuppressWarnings("unused") public void closeCon() { FTPClient ftpClient = null; if (ftpClient != null) { if (ftpClient.isConnected()) { try { ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }// end method closeCon} public static void downLoad(String name, String path) throws IOException { System.err.println("-------- "); InputStream in; OutputStream out; in = new FileInputStream(path); name = URLEncoder.encode(name, "UTF-8"); out = new FileOutputStream(path); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b)) != -1) { out.write(b, 0, len); } out.flush(); out.close(); in.close(); // 设置响应头,对文件进行url编码 // 第三步:老套路,开始copy }}
package com.wbr.app.read.task;import java.io.File;import java.io.IOException;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import org.apache.commons.lang.StringEscapeUtils;import org.apache.log4j.Logger;import com.wbr.app.read.ftp.FtpUtil;import com.wbr.app.read.util.PropertiesLoader;/** * * - FTP 服务器 下载目录下的所有文件到本地(FTP模式 非 SFTP模式) * * @author panpan.wang * @version 1.0 (2018年3月13日 ) */public class DownFtpFilesTask { private static Logger logger = Logger.getLogger(DownFtpFilesTask.class); static PropertiesLoader loader = new PropertiesLoader("readData.properties", "UTF-8"); static final String HOST = loader.getProperty("host"); static final String PORT = loader.getProperty("port"); static final String USERNAME = loader.getProperty("username"); static final String PASSWORD = loader.getProperty("password"); static final String FTPPATH = loader.getProperty("ftpPath"); static final String LOCALPATH = loader.getProperty("localPath"); public static void ftpFileTask() throws IOException, ParseException { SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd"); String ss = s.format(new Date()); String ftpHost = HOST; String ftpUserName = USERNAME; String ftpPassword = PASSWORD; int ftpPort = Integer.valueOf(PORT); String ftpPath = FTPPATH; String localPath = LOCALPATH + ss; if (mkDirectory(localPath)) { logger.info(localPath + " 建立完毕"); } else { logger.info(localPath + " 此目录或许已经存在!"); } // 下载文件 FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath); logger.info("任务结束"); } public static void main(String[] args) { try { ftpFileTask(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } public static boolean mkDirectory(String path) { File file = null; try { file = new File(path); if (!file.exists()) { return file.mkdirs(); } else { return false; } } catch (Exception e) { } finally { file = null; } return false; } public static String istrim(String str) { if (str == null || str.equals("")) { return ""; } else { str = StringEscapeUtils.unescapeJava(str); return str.trim(); } }}
StringUtile 工具类
package com.wbr.app.read.util;import java.io.UnsupportedEncodingException;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.servlet.http.HttpServletRequest;import org.apache.commons.lang3.BooleanUtils;import org.apache.commons.lang3.StringEscapeUtils;import com.google.common.collect.Lists;/** * * - 字符串工具类, 继承org.apache.commons.lang3.StringUtils类 * * @author panpan.wang * @create 2018年3月6日15:18:24 */public class StringUtils extends org.apache.commons.lang3.StringUtils { private static final char SEPARATOR = '_'; private static final String CHARSET_NAME = "UTF-8"; /** * 转换为字节数组 * * @param str * @return */ public static byte[] getBytes(String str) { if (str != null) { try { return str.getBytes(CHARSET_NAME); } catch (UnsupportedEncodingException e) { return null; } } else { return null; } } /** * 转换为Boolean类型 'true', 'on', 'y', 't', 'yes' or '1' (case insensitive) will * return true. Otherwise, false is returned. */ public static Boolean toBoolean(final Object val) { if (val == null) { return false; } return BooleanUtils.toBoolean(val.toString()) || "1".equals(val.toString()); } /** * 转换为字节数组 * * @param str * @return */ public static String toString(byte[] bytes) { try { return new String(bytes, CHARSET_NAME); } catch (UnsupportedEncodingException e) { return EMPTY; } } /** * 如果对象为空,则使用defaultVal值 see: ObjectUtils.toString(obj, defaultVal) * * @param obj * @param defaultVal * @return */ public static String toString(final Object obj, final String defaultVal) { return obj == null ? defaultVal : obj.toString(); } /** * 是否包含字符串 * * @param str * 验证字符串 * @param strs * 字符串组 * @return 包含返回true */ public static boolean inString(String str, String... strs) { if (str != null) { for (String s : strs) { if (str.equals(trim(s))) { return true; } } } return false; } /** * 替换掉HTML标签方法 */ public static String replaceHtml(String html) { if (isBlank(html)) { return ""; } String regEx = "<.+?>"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(html); String s = m.replaceAll(""); return s; } /** * 替换为手机识别的HTML,去掉样式及属性,保留回车。 * * @param html * @return */ public static String replaceMobileHtml(String html) { if (html == null) { return ""; } return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>"); } /** * 替换为手机识别的HTML,去掉样式及属性,保留回车。 * * @param txt * @return */ // public static String toHtml(String txt){ // if (txt == null){ // return ""; // } // return replace(replace(Encodes.escapeHtml(txt), "\n", ""), "\t", // " "); // } /** * 缩略字符串(不区分中英文字符) * * @param str * 目标字符串 * @param length * 截取长度 * @return */ public static String abbr(String str, int length) { if (str == null) { return ""; } try { StringBuilder sb = new StringBuilder(); int currentLength = 0; for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)) .toCharArray()) { currentLength += String.valueOf(c).getBytes("GBK").length; if (currentLength <= length - 3) { sb.append(c); } else { sb.append("..."); break; } } return sb.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; } public static String abbr2(String param, int length) { if (param == null) { return ""; } StringBuffer result = new StringBuffer(); int n = 0; char temp; boolean isCode = false; // 是不是HTML代码 boolean isHTML = false; // 是不是HTML特殊字符,如 for (int i = 0; i < param.length(); i++) { temp = param.charAt(i); if (temp == '<') { isCode = true; } else if (temp == '&') { isHTML = true; } else if (temp == '>' && isCode) { n = n - 1; isCode = false; } else if (temp == ';' && isHTML) { isHTML = false; } try { if (!isCode && !isHTML) { n += String.valueOf(temp).getBytes("GBK").length; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (n <= length - 3) { result.append(temp); } else { result.append("..."); break; } } // 取出截取字符串中的HTML标记 String temp_result = result.toString().replaceAll("(>)[^<>]*( ]*/?>", ""); // 去掉成对的HTML标记 temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?) ", "$2"); // 用正则表达式取出标记 Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>"); Matcher m = p.matcher(temp_result); ListendHTML = Lists.newArrayList(); while (m.find()) { endHTML.add(m.group(1)); } // 补全不成对的HTML标记 for (int i = endHTML.size() - 1; i >= 0; i--) { result.append(" "); } return result.toString(); } /** * 转换为Double类型 */ public static Double toDouble(Object val) { if (val == null) { return 0D; } try { return Double.valueOf(trim(val.toString())); } catch (Exception e) { return 0D; } } /** * 转换为Float类型 */ public static Float toFloat(Object val) { return toDouble(val).floatValue(); } /** * 转换为Long类型 */ public static Long toLong(Object val) { return toDouble(val).longValue(); } /** * 转换为Integer类型 */ public static Integer toInteger(Object val) { return toLong(val).intValue(); } // /** // * 获得i18n字符串 // */ // public static String getMessage(String code, Object[] args) { // LocaleResolver localLocaleResolver = (LocaleResolver) // SpringContextHolder.getBean(LocaleResolver.class); // HttpServletRequest request = // ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); // Locale localLocale = localLocaleResolver.resolveLocale(request); // return SpringContextHolder.getApplicationContext().getMessage(code, args, // localLocale); // } /** * 获得用户远程地址 */ public static String getRemoteAddr(HttpServletRequest request) { String remoteAddr = request.getHeader("X-Real-IP"); if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("X-Forwarded-For"); } else if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("Proxy-Client-IP"); } else if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("WL-Proxy-Client-IP"); } return remoteAddr != null ? remoteAddr : request.getRemoteAddr(); } /** * 驼峰命名法工具 * * @return toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCamelCase(String s) { if (s == null) { return null; } s = s.toLowerCase(); StringBuilder sb = new StringBuilder(s.length()); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == SEPARATOR) { upperCase = true; } else if (upperCase) { sb.append(Character.toUpperCase(c)); upperCase = false; } else { sb.append(c); } } return sb.toString(); } /** * 驼峰命名法工具 * * @return toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCapitalizeCamelCase(String s) { if (s == null) { return null; } s = toCamelCase(s); return s.substring(0, 1).toUpperCase() + s.substring(1); } /** * 驼峰命名法工具 * * @return toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toUnderScoreCase(String s) { if (s == null) { return null; } StringBuilder sb = new StringBuilder(); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean nextUpperCase = true; if (i < (s.length() - 1)) { nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); } if ((i > 0) && Character.isUpperCase(c)) { if (!upperCase || !nextUpperCase) { sb.append(SEPARATOR); } upperCase = true; } else { upperCase = false; } sb.append(Character.toLowerCase(c)); } return sb.toString(); } /** * 转换为JS获取对象值,生成三目运算返回结果 * * @param objectString * 对象串 例如:row.user.id * 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id */ public static String jsGetVal(String objectString) { StringBuilder result = new StringBuilder(); StringBuilder val = new StringBuilder(); String[] vals = split(objectString, "."); for (int i = 0; i < vals.length; i++) { val.append("." + vals[i]); result.append("!" + (val.substring(1)) + "?'':"); } result.append(val.substring(1)); return result.toString(); }}