/** * 检查指定的字符串是否为空 * isStringEmpt("")= true * isStringEmpt(null) = true * isStringEmpt(" ") = true * isStringEmpt(" d ") = false * @param inStr 被检查的字符串 * @return true:被检查字符串为空; false:被检查的字符串不为空 */ public static boolean isStringEmpt(String inStr) { int strLen; if(inStr == null || (strLen = inStr.length())== 0 ) { return true; } for(int i = 0;i <strLen;i++) { if ((Character.isWhitespace(inStr.charAt(i)) == false)) { return false; } } return true; } /** * 检查对象是否为数字型字符串。 */ public static boolean isNumeric(Object obj) { if (obj == null) { return false; } String str = obj.toString(); int sz = str.length(); for (int i = 0; i < sz; i++) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } /** * 把通用字符编码的字符串转化为汉字编码。 */ public static String unicodeToChinese(String unicode) { StringBuilder out = new StringBuilder(); if (!isStringEmpt(unicode)) { for (int i = 0; i < unicode.length(); i++) { out.append(unicode.charAt(i)); } } return out.toString(); } /** * 过滤不可见字符 */ public static String stripNonValidXMLCharacters(String input) { if (input == null || ("".equals(input))) return ""; StringBuilder out = new StringBuilder(); char current; for (int i = 0; i < input.length(); i++) { current = input.charAt(i); if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD)) || ((current >= 0x10000) && (current <= 0x10FFFF))) out.append(current); } return out.toString(); } /** * 从给定的文件路径读取文件并把文件内容转化成Byte[] * @param filename 文件的绝对路径路径,比如:D://Program Files//Genuitec//myEclipse//AUTOMATIC_MID_LAYER//src//com//configure//trans.xml * @return 文件内容的Byte[] * @throws IOException */ public static byte[] readFileToByte(String filename) throws IOException { File file =new File(filename); if(filename==null || filename.equals("")) { throw new NullPointerException("filename is empty"); } long len = file.length(); byte[] bytes = new byte[(int)len]; BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(file)); int r = bufferedInputStream.read( bytes ); if (r != len) throw new IOException("faild"); bufferedInputStream.close(); return bytes; } /** * 将byte[]转化成字符串String * @param inByte * @return * @throws IOException */ public static String byteToString(byte[] inByte) throws IOException { String returnStr = ""; try { returnStr = new String(inByte,"utf-8"); } catch (UnsupportedEncodingException e) { throw new IOException(e); } return returnStr; } /** * 将字符串写入指定的文件 * @param data 需写入的字符串 * @param filename 写入的文件名,包括绝对路径,比如D://ssh//test.txt */ public static void writeStringToFile(String data,String filename) { File file =new File(filename); file.getParentFile().mkdirs(); BufferedOutputStream bufferedOutputStream; try { bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); if(data!=null && !data.equals("")) { bufferedOutputStream.write(data.getBytes("utf-8")); } bufferedOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } /** *将指定字符串追加到文件末尾 *@param fileName 被追加的文件绝对路径及文件名,比如D://ssh//test.txt *@param content 追加的文件内容 */ public static void appendStringToFile(String fileName, String content) { try { //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 FileWriter writer = new FileWriter(fileName, true); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 将byte[]转换成base64编码的字符串 * @param 需进行base64编码的byte[] * @return 经base64编码的字符串 */ public static String encode(byte[] data) { char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; StringBuffer sb = new StringBuffer(); int len = data.length; int i = 0; int b1, b2, b3; while (i < len) { b1 = data[i++] & 0xff; if (i == len) { sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[(b1 & 0x3) << 4]); sb.append("=="); break; } b2 = data[i++] & 0xff; if (i == len) { sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); sb.append("="); break; } b3 = data[i++] & 0xff; sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]); sb.append(base64EncodeChars[b3 & 0x3f]); } return sb.toString(); } /** * 将base64编码的字符串解码, 返回byte数组 * @param str 经base64编码的字符串 * @return base64编码的字符串还原成的byte[] */ public static byte[] decode(String str) { byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1 }; //System.out.println("str===" + str); if (str == null){ return null; } byte[] data = null; try { data = str.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } int len = data.length; ByteArrayOutputStream buf = new ByteArrayOutputStream(len); int i = 0; int b1, b2, b3, b4; while (i < len) { /* b1 */ do { b1 = base64DecodeChars[data[i++]]; } while (i < len && b1 == -1); if (b1 == -1) { break; } /* b2 */ do { b2 = base64DecodeChars[data[i++]]; } while (i < len && b2 == -1); if (b2 == -1) { break; } buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4))); /* b3 */ do { b3 = data[i++]; if (b3 == 61) { return buf.toByteArray(); } b3 = base64DecodeChars[b3]; } while (i < len && b3 == -1); if (b3 == -1) { break; } buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); /* b4 */ do { b4 = data[i++]; if (b4 == 61) { return buf.toByteArray(); } b4 = base64DecodeChars[b4]; } while (i < len && b4 == -1); if (b4 == -1) { break; } buf.write((int) (((b3 & 0x03) << 6) | b4)); } return buf.toByteArray(); } /** * 将字符串编码成base64格式的字符串 * @param str 被base64编码的字符串 * @return 经base64编码后的字符串 */ public static String encodeToStr(String str) { try { byte[] data = str.getBytes("utf-8"); return encode(data); } catch (UnsupportedEncodingException e) { return null; } } /** * 将base64编码后的字符串反编码成原字符串 * @param str 经过base64编码后的字符串 * @return 反编码还原后的字符串 */ public static String decodeToString(String str) { byte[] temp = decode(str); String returnStr= ""; try { returnStr = new String(temp,"utf-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returnStr; } /** * 模拟httpPost方式发送数据 * @param url 目标地址 * @param realData 需发送的数据字符串 * 返回为空,表示发送失败 */ public static String post(String url, String realData) { try { int len = 0; byte[] b = new byte[1024]; long start = System.currentTimeMillis(); int startIndex = url.indexOf("//") + 2; String urlTemp = url.substring(startIndex); String hostInfo = urlTemp.substring(0, urlTemp.indexOf("/")); String[] hostInfos = hostInfo.split(":"); String host = hostInfos[0]; int port = 80; if (hostInfos.length > 1) { port = Integer.parseInt(hostInfos[1].trim()); } int retry = 3; Socket proxySocket = null; if (!host.equals("")) { while (retry-- > 0) { try { proxySocket = new Socket(host, port); proxySocket.setSoTimeout(10000); break; } catch (Exception e) { } Thread.sleep(500); } } if (proxySocket == null) { return null; } StringBuffer reqData = new StringBuffer(""); reqData.append("POST "); reqData.append(url); reqData.append(" HTTP/1.1/r/n"); reqData .append("Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*/r/n"); reqData.append("Accept-Language: zh-cn/r/n"); reqData .append("Content-Type: application/x-www-form-urlencoded/r/n"); reqData.append("Accept-Encoding: gzip, deflate/r/n"); reqData .append("User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)/r/n"); reqData.append("Host:"); reqData.append(host); reqData.append(":"); reqData.append(port + "/r/n"); reqData.append("Pragma: no-cache/r/n"); reqData.append("Coonection: close/r/n"); reqData.append("Content-Length: "); String temp = realData.toString().replaceAll("/r/n", ""); temp = temp.replaceAll("//+", "%2B"); reqData.append(temp.getBytes("utf-8").length + "/r/n"); reqData.append("/r/n"); reqData.append(temp); OutputStream pos = proxySocket.getOutputStream(); pos.write(reqData.toString().getBytes("utf-8")); pos.flush(); InputStream pis = proxySocket.getInputStream(); ByteArrayOutputStream respData = new ByteArrayOutputStream(); proxySocket.shutdownOutput(); try { while (true) { len = pis.read(b); if (len <= 0) { pis.close(); break; } respData.write(b, 0, len); } } catch (SocketTimeoutException ee) { //logger.error("读取数据超时..."); } finally { proxySocket.close(); } //logger.info("处理耗时(单位:毫秒):" + (System.currentTimeMillis() - start)); String respStr = respData.toString("utf-8"); int okIndex = respStr.indexOf(" "); String status = respStr.substring(okIndex, okIndex + 4); if (status.trim().equals("200")) { int lenIndex = respStr.indexOf("Content-Length: "); String rp = respStr.substring(lenIndex + "Content-Length: ".length()); int dataLen = rp.indexOf("<?xml"); rp = rp.substring(dataLen); return rp; } return null; } catch (Exception e) { //logger.error(e.getMessage()); return null; } } /** * 判断是否是邮箱 * liuahang@163.com = true * liuahang@.com = false * liuahang163.com = false * @param email * @return */ public static boolean isEmail(String email) { boolean flag = false; if (Pattern .matches( "^[a-zA-Z0-9_//.//$-]{1,20}@[a-zA-Z0-9]{1,10}(//.[a-zA-Z0-9]{1,5}){1,3}$", email)) { return true; } return flag; } /** * 判断是否是手机号 * 第一位必须为1 * 必须为11位数字 * @param mobileNo * @return */ public static boolean isMobileNo(String mobileNo) { boolean flag = false; if (Pattern.matches("^[1][0-9]{10}", mobileNo)) { return true; } return flag; } /** * 验证身份证号码是否合法 1、15位身份证号码组成: ddddddyymmddxxs共15位,其中: * dddddd为6位的地方代码,根据这6位可以获得该身份证号所在地。 yy为2位的年份代码,是身份证持有人的出身年份。 * mm为2位的月份代码,是身份证持有人的出身月份。 dd为2位的日期代码,是身份证持有人的出身日。 这6位在一起组成了身份证持有人的出生日期。 * xx为2位的顺序码,这个是随机数。 s为1位的性别代码,奇数代表男性,偶数代表女性。 * * 2、18位身份证号码组成: ddddddyyyymmddxxsp共18位,其中: * 其他部分都和15位的相同。年份代码由原来的2位升级到4位。最后一位为校验位。 * * @param idCard * @return */ public static boolean isIdCard(String idCard) { /** 身份证号码1-17位求和权重 */ int[] NUMS = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; /** 校验码结果 */ char[] RESULT = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' }; boolean isValid = true; int num = 0; int sum = 0; int len = idCard.length(); idCard = idCard.toUpperCase(); if (len != 15 && len != 18) { // 位数不正确 return false; } if (!Pattern.matches("[0-9]{15}|([0-9]{17}[0-9X])", idCard)) { // 格式不对 return false; } if (len == 15) { // 15位身份证规则 return isDate(idCard.substring(6, 12)); } else { // 18位身份证规则 if (isDate(idCard.substring(6, 14))) { for (int i = 0; i < 17; i++) { num = Integer.parseInt(idCard.charAt(i) + ""); sum += (num * NUMS[i]); } char c = RESULT[sum % 11]; if (c != idCard.charAt(17)) { return false; } } else { return false; } } return isValid; } /** * 判断日期字符串是否是有效的日期 * * @param date * 输入日期字符串,格式yymmdd(年份后两位+月日)或yyyymmdd(年月日) * @return */ public static boolean isDate(String date) { boolean flag = true; int len = date.length(); String year = ""; String month = ""; String day = ""; if (len == 6) { year = "19" + date.substring(0, 2); month = date.substring(2, 4); day = date.substring(4); } else { year = date.substring(0, 4); month = date.substring(4, 6); day = date.substring(6); } int yearNum = Integer.parseInt(year); int monthNum = Integer.parseInt(month); int dayNum = Integer.parseInt(day); if (!(yearNum >= 1900 && yearNum <= Calendar.getInstance().get(Calendar.YEAR) + 1900)) { return false; } if (!(monthNum >= 1 && monthNum <= 12)) { return false; } if (monthNum == 4 || monthNum == 6 || monthNum == 9 || monthNum == 11) { if (dayNum > 30) {// 小月天数应不大于30天 return false; } } else if (monthNum == 2) { if (isLeapYear(yearNum)) { if (dayNum > 29) {// 闰年二月天数应不大于29天 return false; } } else { if (dayNum > 28) {// 非闰年二月天数应不大于28天 return false; } } } else { if (dayNum >= 318) {// 其他月份天数应不大于31天 return false; } } return flag; } /** * 判断年份是否是闰年 * * @param yearNum * 4位年份数字 * @return */ public static boolean isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return true; } else { return false; } } /** * 将字符串进行MD5加密 * @param md5Str 需要加密的字符串 * @return 经MD5加密后的字符串 */ public static String getMD5(String md5Str) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] bytes = md5.digest(md5Str.getBytes()); StringBuffer sb = new StringBuffer(); String temp = ""; for (byte b : bytes) { temp = Integer.toHexString(b & 0XFF); sb.append(temp.length() == 1 ? "0" + temp : temp); } return sb.toString(); } catch (NoSuchAlgorithmException e) { return null; } } /** * 将14位时间转换成格式:xxx-xx-xx xx:xx * @return */ public static String formateTradTime(String timeStr) { if(timeStr == null || timeStr.equals("")) { return ""; } if(timeStr.length()<12) { return timeStr; } else { StringBuffer bf = new StringBuffer(); bf.append(timeStr.substring(0, 4)); bf.append("-"); bf.append(timeStr.substring(4,6)); bf.append("-"); bf.append(timeStr.substring(6, 8)); bf.append(" "); bf.append(timeStr.substring(8,10)); bf.append(":"); bf.append(timeStr.substring(10,12)); return bf.toString(); } } /** * 将xxx.xx格式的金额转成12位的报文格式 * @param amount * @return */ public static String amountConverter_UI2Msg(String amount) { if (amount == null) { return null; } char[] chMessageAmount = new char[12]; for (int i = 0; i < chMessageAmount.length; i++) { chMessageAmount[i] = '0'; } String[] splitAmount = splitString(amount, '.'); for (int i = 0; i < splitAmount[0].length(); i++) { chMessageAmount[9 - splitAmount[0].length() + 1 + i] = splitAmount[0].charAt(i); } if (splitAmount.length == 2) { for (int i = 0; i < splitAmount[1].length(); i++) { if (i > 1) { break; } chMessageAmount[10 + i] = splitAmount[1].charAt(i); } } return new String(chMessageAmount); } /** * 将12位的报文金额转化成xxx.xx的格式 * @param messageAmount * @return */ public static String amountConverter_Msg2UI(String messageAmount) { if (messageAmount == null) { return null; } char[] strAmount = messageAmount.toCharArray(); boolean isHeadZero = true; ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i = 0; i < strAmount.length; i++) { if (i < (strAmount.length - 3)) { if (strAmount[i] != '0') { isHeadZero = false; } if (!isHeadZero) { baos.write(strAmount[i]); } } else { if (i == (strAmount.length - 2)) { baos.write('.'); } baos.write(strAmount[i]); } } return baos.toString(); } /** * 拆分字符串 * * @param src * 源字符串 * @param signal * 拆分依据 * @return 被拆分的字符串数组 */ public static String[] splitString(String src, char signal) { if (src == null) { return null; } Vector strings = new Vector(); int partIndex = 0; for (int count = 0; count < src.length(); count++) { if (src.toCharArray()[count] == signal) { strings.addElement(src.substring(partIndex, count)); partIndex = count + 1; } } strings.addElement(src.substring(partIndex, src.length())); String[] splittedString = new String[strings.size()]; strings.copyInto(splittedString); return splittedString; } /** * 将xml格式的字符串转换成Map * @author liuhang * @param xml * @return returnMap */ public static Map<String, Object> Dom2Map(String xml){ Document doc = null; try { doc = DocumentHelper.parseText(xml); } catch (DocumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Map<String, Object> map = new HashMap<String, Object>(); if(doc == null) return map; org.dom4j.Element root = doc.getRootElement(); for (Iterator iterator = root.elementIterator(); iterator.hasNext();) { org.dom4j.Element e = (org.dom4j.Element) iterator.next(); //System.out.println(e.getName()); List list = e.elements(); if(list.size() > 0){ map.put(e.getName(), Dom2Map(e)); }else map.put(e.getName(), e.getText()); } Map<String, Object> returnMap = new HashMap<String, Object>(); returnMap.put(root.getName(), map); return returnMap; } /** * 解析节点Element成map * @param e * @return */ public static Map Dom2Map(org.dom4j.Element e){ Map map = new HashMap(); List list = e.elements(); if(list.size() > 0){ for (int i = 0;i < list.size(); i++) { org.dom4j.Element iter = (org.dom4j.Element) list.get(i); List mapList = new ArrayList(); if(iter.elements().size() > 0){ Map m = Dom2Map(iter); if(map.get(iter.getName()) != null){ Object obj = map.get(iter.getName()); if(!obj.getClass().getName().equals("java.util.ArrayList")){ mapList = new ArrayList(); mapList.add(obj); mapList.add(m); } if(obj.getClass().getName().equals("java.util.ArrayList")){ mapList = (List) obj; mapList.add(m); } map.put(iter.getName(), mapList); }else map.put(iter.getName(), m); } else{ if(map.get(iter.getName()) != null){ Object obj = map.get(iter.getName()); if(!obj.getClass().getName().equals("java.util.ArrayList")){ mapList = new ArrayList(); mapList.add(obj); mapList.add(iter.getText()); } if(obj.getClass().getName().equals("java.util.ArrayList")){ mapList = (List) obj; mapList.add(iter.getText()); } map.put(iter.getName(), mapList); }else map.put(iter.getName(), iter.getText()); } } }else map.put(e.getName(), e.getText()); return map; } /** * 通过servlet发送HTTP请求数据 * @param request * @param response * @throws ServletException * @throws IOException */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { byte[] resultByte = null; OutputStream out = response.getOutputStream(); if(resultByte != null){ byte[] ret = resultByte; response.setContentLength(ret.length); out.write(ret); }else{ out.write("".getBytes("UTF-8")); } out.flush(); out.close(); long end = System.currentTimeMillis(); //logger.info("服务处理耗时(单位:毫秒):" + (end - start)); } catch (Exception e) { e.printStackTrace(); //logger.error(e.getMessage()); } } /************************************************************************* **获取WEB-INF/classes目录下配置文件的Java类 ,通常情况下我们将配置文件放在WEB-INF/classes,如何获取这个路径有很多种途径,下面这个类是我通常使用的类,基本上覆盖了所有的文件读取流 * ************************************************************************* /** Returns the URL of the resource on the classpath 11 * @param resource The resource to find 12 * @throws IOException If the resource cannot be found or read 13 * @return The resource 14 */ public static URL getResourceURL(String resource) throws IOException { URL url = null; ClassLoader loader = Utils.class.getClassLoader(); if (loader != null) url = loader.getResource(resource); if (url == null) url = ClassLoader.getSystemResource(resource); if (url == null) throw new IOException("Could not find resource " + resource); return url; } /** *//** Returns the URL of the resource on the classpath 25 * @param loader The classloader used to load the resource 26 * @param resource The resource to find 27 * @throws IOException If the resource cannot be found or read 28 * @return The resource 29 */ public static URL getResourceURL(ClassLoader loader, String resource) throws IOException { URL url = null; if (loader != null) url = loader.getResource(resource); if (url == null) url = ClassLoader.getSystemResource(resource); if (url == null) throw new IOException("Could not find resource " + resource); return url; } /** *//** Returns a resource on the classpath as a Stream object 39 * @param resource The resource to find 40 * @throws IOException If the resource cannot be found or read 41 * @return The resource 42 */ public static InputStream getResourceAsStream(String resource) throws IOException { InputStream in = null; ClassLoader loader = Utils.class.getClassLoader(); if (loader != null) in = loader.getResourceAsStream(resource); if (in == null) in = ClassLoader.getSystemResourceAsStream(resource); if (in == null) throw new IOException("Could not find resource " + resource); return in; } /** *//** Returns a resource on the classpath as a Stream object 53 * @param loader The classloader used to load the resource 54 * @param resource The resource to find 55 * @throws IOException If the resource cannot be found or read 56 * @return The resource 57 */ public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException { InputStream in = null; if (loader != null) in = loader.getResourceAsStream(resource); if (in == null) in = ClassLoader.getSystemResourceAsStream(resource); if (in == null) throw new IOException("Could not find resource " + resource); return in; } /** *//** Returns a resource on the classpath as a Properties object 67 * @param resource The resource to find 68 * @throws IOException If the resource cannot be found or read 69 * @return The resource 70 */ public static Properties getResourceAsProperties(String resource) throws IOException { Properties props = new Properties(); InputStream in = null; String propfile = resource; in = getResourceAsStream(propfile); props.load(in); in.close(); return props; } /** *//** Returns a resource on the classpath as a Properties object 83 * @param loader The classloader used to load the resource 84 * @param resource The resource to find 85 * @throws IOException If the resource cannot be found or read 86 * @return The resource 87 */ public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException { Properties props = new Properties(); InputStream in = null; String propfile = resource; in = getResourceAsStream(loader, propfile); props.load(in); in.close(); return props; } /** *//** Returns a resource on the classpath as a Reader object 100 * @param resource The resource to find 101 * @throws IOException If the resource cannot be found or read 102 * @return The resource 103 */ public static InputStreamReader getResourceAsReader(String resource) throws IOException { return new InputStreamReader(getResourceAsStream(resource)); } /** *//** Returns a resource on the classpath as a Reader object 109 * @param loader The classloader used to load the resource 110 * @param resource The resource to find 111 * @throws IOException If the resource cannot be found or read 112 * @return The resource 113 */ public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException { return new InputStreamReader(getResourceAsStream(loader, resource)); } /** *//** Returns a resource on the classpath as a File object 119 * @param resource The resource to find 120 * @throws IOException If the resource cannot be found or read 121 * @return The resource 122 */ public static File getResourceAsFile(String resource) throws IOException { return new File(getResourceURL(resource).getFile()); } /** *//** Returns a resource on the classpath as a File object 128 * @param loader The classloader used to load the resource 129 * @param resource The resource to find 130 * @throws IOException If the resource cannot be found or read 131 * @return The resource 132 */ public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException { return new File(getResourceURL(loader, resource).getFile()); } /// /** * 读取某个文件夹下的所有文件 */ public static boolean readfile(String filepath) throws FileNotFoundException, IOException { try { File file = new File(filepath); if (!file.isDirectory()) { System.out.println("文件"); System.out.println("path=" + file.getPath()); System.out.println("absolutepath=" + file.getAbsolutePath()); System.out.println("name=" + file.getName()); } else if (file.isDirectory()) { System.out.println("文件夹"); String[] filelist = file.list(); for (int i = 0; i < filelist.length; i++) { File readfile = new File(filepath + "//" + filelist[i]); if (!readfile.isDirectory()) { System.out.println("path=" + readfile.getPath()); System.out.println("absolutepath=" + readfile.getAbsolutePath()); System.out.println("name=" + readfile.getName()); } else if (readfile.isDirectory()) { readfile(filepath + "//" + filelist[i]); } } } } catch (FileNotFoundException e) { System.out.println("readfile() Exception:" + e.getMessage()); } return true; } /** * 删除某个文件夹下的所有文件夹和文件 */ public static boolean deletefile(String delpath) throws FileNotFoundException, IOException { try { File file = new File(delpath); if (!file.isDirectory()) { System.out.println("1"); file.delete(); } else if (file.isDirectory()) { System.out.println("2"); String[] filelist = file.list(); for (int i = 0; i < filelist.length; i++) { File delfile = new File(delpath + "//" + filelist[i]); if (!delfile.isDirectory()) { System.out.println("path=" + delfile.getPath()); System.out.println("absolutepath=" + delfile.getAbsolutePath()); System.out.println("name=" + delfile.getName()); delfile.delete(); System.out.println("删除文件成功"); } else if (delfile.isDirectory()) { deletefile(delpath + "//" + filelist[i]); } } file.delete(); } } catch (FileNotFoundException e) { System.out.println("deletefile() Exception:" + e.getMessage()); } return true; } /** * 循环读取文件夹下的文件,并修改文件的部分内容 * @param fileName * @param fileType */ public static void iteratorFile(String fileName,String fileType){ File file=new File(fileName); File[] files=file.listFiles(); for(int i=0;i<files.length;i++){ if(files[i].isDirectory()){ iteratorFile(files[i].getAbsolutePath().replace('//','/'),fileType); }else if(files[i].isFile()){ String file_name=files[i].getAbsolutePath().replace('//','/'); updateFile(new File(file_name),fileType); } } } public static void updateFile(File file,String fileType){ int time=0; if(file.getName().length()>4&&file.getName().substring(file.getName().length()-4).equals(fileType)){ try { int index=file.getAbsolutePath().lastIndexOf('//')+1; String fileName=file.getName(); File file1=new File(file.getAbsolutePath().substring(0,index)+fileName+"_bakj"); System.out.println(file.getAbsolutePath()); BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file))); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file1))); String line=null; while((line=br.readLine())!=null){ bw.write(line.replace("charset=ISO8859_1", "charset=utf-8").replace("charset=iso8859_1","charset=utf-8")+"/n"); } time++; bw.flush(); bw.close(); br.close(); file.delete(); file1.renameTo(new File(file.getAbsolutePath().substring(0,index)+fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } public static String fiterHtmlTag(String str, String tag) { String regxp = "<//s*" + tag + "//s+([^>]*)//s*>"; Pattern pattern = Pattern.compile(regxp); Matcher matcher = pattern.matcher(str); StringBuffer sb = new StringBuffer(); boolean result1 = matcher.find(); while (result1) { matcher.appendReplacement(sb, ""); result1 = matcher.find(); } matcher.appendTail(sb); return sb.toString(); } /** * 过滤Html标签 */ //private final static String regxpForImgTag = "<//s*href//s+([^>]*)//s*>"; // 找出IMG标签 //private final static String regxpForImgTag = "<///s*(html|body)//s*>"; //private final static String regxpForImgTag = "(<//s*(html|body)//s*>)|(<///s*(html|body)//s*>)"; private final static String regxpForImgTag = "<(/|)//s*(body|head)//s*>"; private final static String regxpForHtml = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签 public static String filterHtml(String str) { Pattern pattern = Pattern.compile(regxpForImgTag); Matcher matcher = pattern.matcher(str); StringBuffer sb = new StringBuffer(); boolean result1 = matcher.find(); while (result1) { matcher.appendReplacement(sb, ""); result1 = matcher.find(); } matcher.appendTail(sb); return sb.toString(); } /** * yyyy-MM-d格式的时间转换成Date时间 * @param str * @return */ public static Date stringToDate(String str) { DateFormat formate = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = formate.parse(str); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return date; } /** * 取得当前日期所在周的第一天日期,格式为yyyy-MM-dd * * @param date * @return */ public static String getFirstDayOfWeek(Date date) { Calendar c = new GregorianCalendar(); c.setFirstDayOfWeek(Calendar.MONDAY); c.setTime(date); c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday DateFormat formate = new SimpleDateFormat("yyyy-MM-dd"); String str = formate.format(c.getTime()); return str; } /** * 取得当前日期所在周的最后一天日期,格式为yyyy-MM-dd * * @param date * @return */ public static String getLastDayOfWeek(Date date) { Calendar c = new GregorianCalendar(); c.setFirstDayOfWeek(Calendar.MONDAY); c.setTime(date); c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday DateFormat formate = new SimpleDateFormat("yyyy-MM-dd"); String str = formate.format(c.getTime()); return str; } /** * 将字符串进行MD5加密 * @param md5Str 需要加密的字符串 * @return 经MD5加密后的字符串 */ public static String getMD5(String md5Str) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] bytes = md5.digest(md5Str.getBytes()); StringBuffer sb = new StringBuffer(); String temp = ""; for (byte b : bytes) { temp = Integer.toHexString(b & 0XFF); sb.append(temp.length() == 1 ? "0" + temp : temp); } return sb.toString(); } catch (NoSuchAlgorithmException e) { return null; } }