埃拉托斯特尼筛法检定素数

最后更新于:2022-04-01 20:25:03

埃拉托斯特尼筛法,简称埃氏筛或爱氏筛,是一种由希腊数学家埃拉托斯特尼所提出的一种简单检定素数的算法。要得到自然数n以内的全部素数,必须把不大于根号n的所有素数的倍数剔除,剩下的就是素数。 给出要筛数值的范围n,找出以内的素数。先用2去筛,即把2留下,把2的倍数剔除掉;再用下一个质数,也就是3筛,把3留下,把3的倍数剔除掉;接下去用下一个质数5筛,把5留下,把5的倍数剔除掉;不断重复下去......。 java源码: ~~~ package test1.number; public class Eratosthenes { public static void main(String[] args) { int max = 20; try { max = Integer.parseInt(args[0]); } catch (Exception e) { } boolean[] isprime = new boolean[max + 1]; for (int i = 0; i <= max; i++) isprime[i] = true; isprime[0] = isprime[1] = false; int n = (int) Math.ceil(Math.sqrt(max)); for (int i = 0; i <= n; i++) { if (isprime[i]) for (int j = 2 * i; j <= max; j = j + i) isprime[j] = false; } int largest; for (largest = max; !isprime[largest]; largest--); System.out.println("The largest prime less than or equal to " + max + " is " + largest); } } ~~~ 运行结果: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-05-17_573adb32ca352.jpg)
';

任意位置切分string

最后更新于:2022-04-01 20:25:01

源码: ~~~ package test1.string; import java.util.ArrayList; import java.util.List; public class Split { public static void main(String[] args) { for (String part : getParts("This is an example", 2)) { System.out.println(part); } } private static List getParts(String string, int partitionSize) { List parts = new ArrayList(); int len = string.length(); for (int i = 0; i < len; i += partitionSize) { parts.add(string.substring(i, Math.min(len, i + partitionSize))); } return parts; } } ~~~ 运行结果: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-05-17_573adb3129a7f.jpg)
';

Map取值方法,其中取得多种值,避免null值转换

最后更新于:2022-04-01 20:24:59

~~~ import java.math.BigDecimal; import java.util.Date; import java.util.Map; /** *

* Map取值方法,其中取得多种值,避免null值转换 *

* @author hailan * */ public class MapGetterTool { private Map map; public MapGetterTool(Map map){ this.map = map; } /** *

* 根据Key返回一个Double型 *

* @param key * @return Double */ public Double getDouble(String key){ if(map.get(key)!=null){ if(map.get(key) instanceof Double){ return (Double)map.get(key); }else{ return 0.0; } }else{ return 0.00; } } /** *

* 根据Key返回一个String *

* @param key * @return String */ public String getString(String key){ if(map.get(key)!=null){ if(map.get(key) instanceof String){ return (String)map.get(key); }else{ return null; } }else{ return ""; } } /** *

* 根据Key返回一个Date *

* @param key * @return Date */ public Date getDate(String key){ if(map.get(key)!=null){ if(map.get(key) instanceof Date){ return (Date)map.get(key); }else{ return null; } }else{ return null; } } /** *

* 根据Key返回一个Integer *

* @param key * @return Integer */ public Integer getInteger(String key){ if(map.get(key)!=null){ if(map.get(key) instanceof Integer){ return (Integer)map.get(key); }else{ return null; } }else{ return 0; } } /** *

* 根据一个Key返回一个Map *

* @param key * @return Map */ @SuppressWarnings("unchecked") public Map getMap(String key){ if(map.get(key)!=null){ if(map.get(key) instanceof Map){ return (Map)map.get(key); }else{ return null; } }else{ return null; } } /** *

* 根据key返回BigDecimal * 如果为null,则返回 new BigDecimal(0) *

* @param key * @return BigDecimal */ public BigDecimal getBigDecimal(String key){ if(map.containsKey(key)){ if(map.get(key) instanceof BigDecimal){ return (BigDecimal)map.get(key); }else{ return new BigDecimal(0); } }else{ return new BigDecimal(0); } } } ~~~
';

HashMap与Bean互转

最后更新于:2022-04-01 20:24:57

~~~ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * HashMap与Bean互转工具类 * * @author hailan * @time 2015-10-12下午05:56:34 */ public class HashMapBeanTools { /** * HashMap转换成JavaBean * * @author hailan * @time 下午05:57:16 * @param map * @param cls * @return */ public static Object hashMapToJavaBean(HashMap map, Class cls) { Object obj = null; try { obj = cls.newInstance(); } catch (Exception e) { e.printStackTrace(); } // 取出bean里的所有方法 Method[] methods = cls.getMethods(); for (int i = 0; i < methods.length; i++) { // 取方法名 String method = methods[i].getName(); // 取出方法的类型 Class[] cc = methods[i].getParameterTypes(); if (cc.length != 1) continue; // 如果方法名没有以set开头的则退出本次for if (!method.startsWith("set") ) continue; // 类型 String type = cc[0].getSimpleName(); try { // Object value = method.substring(3,4).toLowerCase().concat(method.substring(4)); // 如果map里有该key if (map.containsKey(value)) { // 调用其底层方法 setValue(type, map.get(value), i, methods, obj); } } catch (Exception e) { e.printStackTrace(); } } return obj; } /** * 调用底层方法设置值 * * @author hailan * @time 下午06:01:56 * @param type * @param value * @param i * @param method * @param bean * @throws Exception */ private static void setValue(String type, Object value, int i, Method[] method, Object bean) throws Exception { if (value != null && !value.equals("")) { try { if (type.equals("String")) { // 第一个参数:从中调用基础方法的对象 第二个参数:用于方法调用的参数 method[i].invoke(bean, new Object[] { value }); } else if (type.equals("int") || type.equals("Integer")) { method[i].invoke(bean, new Object[] { new Integer("" + value) }); } else if (type.equals("BigDecimal")) { method[i].invoke(bean, new Object[] { new BigDecimal((String)value) }); } else if (type.equals("long") || type.equals("Long")) { method[i].invoke(bean, new Object[] { new Long("" + value) }); } else if (type.equals("boolean") || type.equals("Boolean")) { method[i].invoke(bean, new Object[] { Boolean.valueOf("" + value) }); } else if (type.equals("Date")) { Date date = null; if (value.getClass().getName().equals("java.util.Date")) { date = (Date) value; } else { //根据文件内的格式不同修改,时间格式太多在此不做通用格式处理。 if (value.toString().length() > 10){ String format = "yyyy-MM-dd HHmmss"; date = parseDateTime("" + value, format); } else if (value.toString().length() == 10){ String format = "yyyy-MM-dd"; date = parseDateTime("" + value, format); } else if (value.toString().length() == 8){ String format = "yyyyMMdd"; date = parseDateTime("" + value, format); } else if (value.toString().length() == 14){ String format = "yyyyMMddHHmmss"; date = parseDateTime("" + value, format); }else if (value.toString().length() == 6){ String format = "HHmmss"; date = parseDateTime("" + value, format); } } if (date != null) { method[i].invoke(bean, new Object[] { date }); } } else if (type.equals("byte[]")) { method[i].invoke(bean, new Object[] { new String(value + "").getBytes() }); } } catch (Exception e) { e.printStackTrace(); throw e; } } } /** * 日期格式转换 * * @author hailan * @time 下午06:02:59 * @param dateValue * @param format * @return */ private static Date parseDateTime(String dateValue, String format) { SimpleDateFormat obj = new SimpleDateFormat(format); try { return obj.parse(dateValue); } catch (Exception e) { e.printStackTrace(); } return null; } public static Map hashJavaBeanToMap(Object ojt) { Class cls = ojt.getClass(); Field[] field = cls.getDeclaredFields(); HashMap mapbean = new HashMap(); for(int i=0;i ';

运算工具(提供精确的浮点数运算,包括加减乘除和四舍五入)

最后更新于:2022-04-01 20:24:54

~~~ import java.math.BigDecimal; /** * 运算工具 * * 提供精确的浮点数运算,包括加减乘除和四舍五入 * * @author lchhh0005 * */ public class ArithTool { // 默认除法算法精确度 private static final int DEF_DIV_SCALE = 10; private ArithTool() { } /** * 提供精确的加法运算 * @param v1 * @param v2 * @return */ public static double add(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2).doubleValue(); } /** * 提供精确的减法运算 * @param v1 * @param v2 * @return */ public static double sub(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.subtract(b2).doubleValue(); } /** * 提供精确的乘法运算 * @param v1 * @param v2 * @return */ public static double mul(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.multiply(b2).doubleValue(); } /** * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 * 小数点后10位,以后的数字四舍五入 * * @param v1 * @param v2 * @return */ public static double div(double v1, double v2) { return div(v1, v2, DEF_DIV_SCALE); } /** * 提供(相对)精确的除法运算,当发生除不尽的情况时,由scale参数 * 指定精度,以后的数字四舍五入 * * @param v1 * @param v2 * @param scale * @return */ public static double div(double v1, double v2, int scale) { if(scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /** * 提供精确的小数位四舍五入处理 * * @param v 需要四舍五入的数字 * @param scale 小数点后保留几位 * @return 四舍五入后的结果 */ public static double round(double v, int scale) { if(scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } } ~~~
';

Base64

最后更新于:2022-04-01 20:24:52

Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。Base64编码可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为128-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base64编码具有不可读性,即所编码的数据不会被人用肉眼所直接看到。 ## 一、编码规则 Base64编码的思想是是采用64个基本的ASCII码字符对数据进行重新编码。它将需要编码的数据拆分成字节数组。以3个字节为一组。按顺序排列24 位数据,再把这24位数据分成4组,即每组6位。再在每组的的最高位前补两个0凑足一个字节。这样就把一个3字节为一组的数据重新编码成了4个字节。当所要编码的数据的字节数不是3的整倍数,也就是说在分组时最后一组不够3个字节。这时在最后一组填充1到2个0字节。并在最后编码完成后在结尾添加1到2个 “=”。 例:将对ABC进行BASE64编码: 1、首先取ABC对应的ASCII码值。A(65)B(66)C(67); 2、再取二进制值A(01000001)B(01000010)C(01000011); 3、然后把这三个字节的二进制码接起来(010000010100001001000011); 4、 再以6位为单位分成4个数据块,并在最高位填充两个0后形成4个字节的编码后的值,(00010000)(00010100)(00001001)(00000011),其中蓝色部分为真实数据; 5、再把这四个字节数据转化成10进制数得(16)(20)(9)(3); 6、最后根据BASE64给出的64个基本字符表,查出对应的ASCII码字符(Q)(U)(J)(D),这里的值实际就是数据在字符表中的索引。 注:BASE64字符表:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ ## 二、解码规则 解码过程就是把4个字节再还原成3个字节再根据不同的数据形式把字节数组重新整理成数据。 ## 三、java程序 ~~~ import java.io.ByteArrayOutputStream; import java.io.IOException; public class Base64 { // Create arrays to hold the base64 characters and a // lookup for base64 chars private static byte[] base64Alphabet; /** * The base length. */ static final int BASELENGTH = 255; /** * Chunk separator per RFC 2045 section 2.1. * * @see RFC 2045 section 2.1 */ static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes(); /** * Chunk size per RFC 2045 section 6.8. * *

* The {@value} character limit does not count the trailing CRLF, but counts * all other characters, including any equal signs. *

* * @see RFC 2045 section 6.8 */ static final int CHUNK_SIZE = 76; /** * Used to calculate the number of bits in a byte. */ static final int EIGHTBIT = 8; /** * Used to get the number of Quadruples. */ static final int FOURBYTE = 4; private static byte[] lookUpBase64Alphabet; /** * Lookup length. */ static final int LOOKUPLENGTH = 64; /** * Byte used to pad output. */ static final byte PAD = (byte) '='; /** * Used to test the sign of a byte. */ static final int SIGN = -128; /** * Used when encoding something which has fewer than 24 bits. */ static final int SIXTEENBIT = 16; /** * Used to determine how many bits data contains. */ static final int TWENTYFOURBITGROUP = 24; // Populating the lookup and character arrays static { lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; base64Alphabet = new byte[BASELENGTH]; for (int i = 0; i < BASELENGTH; i++) { base64Alphabet[i] = (byte) -1; } for (int i = 'Z'; i >= 'A'; i--) { base64Alphabet[i] = (byte) (i - 'A'); } for (int i = 'z'; i >= 'a'; i--) { base64Alphabet[i] = (byte) (i - 'a' + 26); } for (int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i - '0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; for (int i = 0; i <= 25; i++) { lookUpBase64Alphabet[i] = (byte) ('A' + i); } for (int i = 26, j = 0; i <= 51; i++, j++) { lookUpBase64Alphabet[i] = (byte) ('a' + j); } for (int i = 52, j = 0; i <= 61; i++, j++) { lookUpBase64Alphabet[i] = (byte) ('0' + j); } lookUpBase64Alphabet[62] = (byte) '+'; lookUpBase64Alphabet[63] = (byte) '/'; } /** * Decodes Base64 data into octects * * @param base64Data * Byte array containing Base64 data * @return Array containing decoded data. */ public static byte[] decodeBase64(byte[] base64Data) { // RFC 2045 requires that we discard ALL non-Base64 characters base64Data = discardNonBase64(base64Data); // handle the edge case, so we don't have to worry about it // later if (base64Data.length == 0) { return new byte[0]; } int numberQuadruple = base64Data.length / FOURBYTE; byte decodedData[] = null; byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0; // Throw away anything not in base64Data int encodedIndex = 0; int dataIndex = 0; { // this sizes the output array properly - rlw int lastData = base64Data.length; // ignore the '=' padding while (base64Data[lastData - 1] == PAD) { if (--lastData == 0) { return new byte[0]; } } decodedData = new byte[lastData - numberQuadruple]; } for (int i = 0; i < numberQuadruple; i++) { dataIndex = i * 4; marker0 = base64Data[dataIndex + 2]; marker1 = base64Data[dataIndex + 3]; b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex + 1]]; if (marker0 != PAD && marker1 != PAD) { // No PAD e.g 3cQl b3 = base64Alphabet[marker0]; b4 = base64Alphabet[marker1]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); } else if (marker0 == PAD) { // Two PAD e.g. 3c[Pad][Pad] decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); } else if (marker1 == PAD) { // One PAD e.g. 3cQ[Pad] b3 = base64Alphabet[marker0]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); } encodedIndex += 3; } return decodedData; } /** * Discards any characters outside of the base64 alphabet, per the * requirements on page 25 of RFC 2045 - "Any characters outside of the * base64 alphabet are to be ignored in base64 encoded data." * * @param data * The base-64 encoded data to groom * @return The data, less non-base64 characters (see RFC 2045). */ static byte[] discardNonBase64(byte[] data) { byte groomedData[] = new byte[data.length]; int bytesCopied = 0; for (int i = 0; i < data.length; i++) { if (isBase64(data[i])) { groomedData[bytesCopied++] = data[i]; } } byte packedData[] = new byte[bytesCopied]; System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); return packedData; } /** * Discards any whitespace from a base-64 encoded block. * * @param data * The base-64 encoded data to discard the whitespace from. * @return The data, less whitespace (see RFC 2045). */ static byte[] discardWhitespace(byte[] data) { byte groomedData[] = new byte[data.length]; int bytesCopied = 0; for (int i = 0; i < data.length; i++) { switch (data[i]) { case (byte) ' ': case (byte) '\n': case (byte) '\r': case (byte) '\t': break; default: groomedData[bytesCopied++] = data[i]; } } byte packedData[] = new byte[bytesCopied]; System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); return packedData; } /** * Encodes binary data using the base64 algorithm but does not chunk the * output. * * @param binaryData * binary data to encode * @return Base64 characters */ public static byte[] encodeBase64(byte[] binaryData) { return encodeBase64(binaryData, false); } /** * Encodes binary data using the base64 algorithm, optionally chunking the * output into 76 character blocks. * * @param binaryData * Array containing binary data to encode. * @param isChunked * if isChunked is true this encoder will chunk the base64 output * into 76 character blocks * @return Base64-encoded data. */ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { // data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character // sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math .ceil((float) encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; // log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; // log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; // log.debug( "val2 = " + val2 ); // log.debug( "k4 = " + (k<<4) ); // log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte) (b1 & 0x03); // log.debug("b1=" + b1); // log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy(CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } /** * Encodes binary data using the base64 algorithm and chunks the encoded * output into 76 character blocks * * @param binaryData * binary data to encode * @return Base64 characters chunked in 76 character blocks */ public static byte[] encodeBase64Chunked(byte[] binaryData) { return encodeBase64(binaryData, true); } /** * Tests a given byte array to see if it contains only valid characters * within the Base64 alphabet. * * @param arrayOctect * byte array to test * @return true if all bytes are valid characters in the Base64 alphabet or * if the byte array is empty; false, otherwise */ public static boolean isArrayByteBase64(byte[] arrayOctect) { arrayOctect = discardWhitespace(arrayOctect); int length = arrayOctect.length; if (length == 0) { // shouldn't a 0 length array be valid base64 data? // return false; return true; } for (int i = 0; i < length; i++) { if (!isBase64(arrayOctect[i])) { return false; } } return true; } private static boolean isBase64(byte octect) { if (octect == PAD) { return true; } else if (base64Alphabet[0xff & octect] == -1) { return false; } else { return true; } } /** * Decodes a byte[] containing containing characters in the Base64 alphabet. * * @param pArray * A byte array containing Base64 character data * @return a byte array containing binary data */ public byte[] decode(byte[] pArray) { return decodeBase64(pArray); } /** * Encodes a byte[] containing binary data, into a byte[] containing * characters in the Base64 alphabet. * * @param pArray * a byte array containing binary data * @return A byte array containing only Base64 character data */ public byte[] encode(byte[] pArray) { return encodeBase64(pArray, false); } public static byte[] encodeXml(byte src[]) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream text_os = new ByteArrayOutputStream(); byte tag_left = (byte) '<'; byte tag_right = (byte) '>'; boolean begin = false; boolean in_tag = false; for (int i = 0; i < src.length; i++) { byte b = src[i]; if (begin == false && b == tag_left) begin = true; if (b == tag_left) in_tag = true; else if (b == tag_right) in_tag = false; if (!begin) continue; if (in_tag || b == tag_right) { if (b == tag_left) { byte[] text = text_os.toByteArray(); try { baos.write(encodeBase64(text)); } catch (IOException e) { e.printStackTrace(); } text_os.reset(); } baos.write(b); } else { text_os.write(b); } } return baos.toByteArray(); } } ~~~
';

操作XML

最后更新于:2022-04-01 20:24:50

~~~ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.xml.sax.SAXException; public class XmlUtil { private Document document; List elements = new ArrayList(); public static XmlUtil getInstance() { return new XmlUtil(); } private XmlUtil() { } public void load(String url) throws Exception { FileInputStream in = new FileInputStream(url); load(in); } public void load(File file) throws Exception { FileInputStream in = new FileInputStream(file); load(in); } public void load(InputStream in) throws Exception { try { SAXReader reader = new SAXReader(); document = reader.read(in); this.elements = getAllElements(getRootElement()); } finally { in.close(); } } public static Document createDocument() { Document document = DocumentFactory.getInstance().createDocument(); document.setXMLEncoding("GBK"); return document; } public List getAllElements(Element element) { List elements = new ArrayList(); if (element.elements().size() == 0) { elements.add(element); return elements; } else { elements.add(element); for (Object o : element.elements()) { Element e = (Element) o; elements.addAll(getAllElements(e)); } return elements; } } public List findByPath(String path) { return getRootElement().elements(path); } public Element findById(String id) { List ele = findByAttribute("id", id); if (ele.size() > 0) return ele.get(0); return null; } public List findByAttribute(String attrName, String attrValue) { List ele = new ArrayList(); for (Element e : this.elements) { Attribute attr = e.attribute(attrName); if (attr != null && attrValue.equals(attr.getValue())) { ele.add(e); } } return ele; } public List getElements() { return elements; } public void setElements(List elements) { this.elements = elements; } public int findElementIndex(Element e) { int index = this.elements.indexOf(e); return index > 0 ? index - 1 : index; } public void updateElement(Element element, int index) { Element e = this.elements.get(index); this.elements.set(index, element); removeElement(index); e.getParent().add(element); } public void addElement(Element parentElement, Element e) { parentElement.add(e); this.elements.add(e); } public boolean removeElement(Element e) { this.elements.remove(e); return e.getParent().remove(e); } public boolean removeElement(int index) { this.elements.remove(index); Element e = this.elements.get(index); return e.getParent().remove(e); } public Element getRootElement() { return document.getRootElement(); } public String getEncoding() { return document.getXMLEncoding(); } public void setEncoding(String encoding) { document.setXMLEncoding(encoding); } public Document getDocument() { return document; } public void setDocument(Document document) { this.document = document; this.elements = getAllElements(getRootElement()); } public void save(String url) throws SAXException, IOException { FileOutputStream out = new FileOutputStream(url); save(out); out.close(); } public void save(File file) throws SAXException, IOException { FileOutputStream out = new FileOutputStream(file); save(out); out.close(); } public void save(OutputStream out) throws SAXException, IOException { out.write(document.asXML().getBytes()); } public void dispose() { this.elements.clear(); } } ~~~
';

字符串全半角互转

最后更新于:2022-04-01 20:24:48

~~~
/**
 * 
*
功能说明
* 字符串全半角互转 *
* @author hailan */ public class SBCChange { // public static void main(String[] args) { // // String QJstr = "全角转半角DAO喆4 "; // System.out.println(QJstr.length()+"=length"); // QJstr.replaceAll("[ ]", ""); // System.out.println(QJstr.length()+"=replacelengthr"); // String ToDBCres = ToDBC(QJstr); // System.out.println(QJstr + "\nDB" + ToDBCres); // // String QBres = BQchange(QJstr); // System.out.println(QJstr + "\nBQ" + QBres); // } // 半角转全角 /** * 功能说明 * 半角汉字转全角汉字 * @param QJstr 半角 * @return 全角字符串 *

* 例如:
* 使用例子说明 * String a = BQchange("赞同") *

*/ public static final String BQchange(String QJstr) { String outStr = ""; String Tstr = ""; byte[] b = null; for (int i = 0; i < QJstr.length(); i++) { try { Tstr = QJstr.substring(i, i + 1); b = Tstr.getBytes("unicode"); } catch (java.io.UnsupportedEncodingException e) { e.printStackTrace(); } if (b[3] != -1) { b[2] = (byte) (b[2] - 32); b[3] = -1; try { outStr = outStr + new String(b, "unicode"); } catch (java.io.UnsupportedEncodingException e) { e.printStackTrace(); } } else outStr = outStr + Tstr; } return outStr; } /** * 功能说明 * 全角转半角 * @param input 全角字符串 * @return *

* 例如:
* 使用例子说明 * String a = ToDBC("re") *

*/ public static String ToDBC(String input) { char[] c = input.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == 12288) { c[i] = (char) 32; continue; } if (c[i] > 65280 && c[i] < 65375) c[i] = (char) (c[i] - 65248); } return new String(c); } } ~~~
';

文件操作

最后更新于:2022-04-01 20:24:45

~~~ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; /** * * @author 海兰 */ public class FileUtil { public static String[] getUtfLines(String path) throws IOException { byte[] filebyte=readFile(path); String filestr=new String(filebyte,"UTF-8"); String[] rev=filestr.split("\n"); return rev; } public static String[] getLines(String path) throws IOException { byte[] filebyte=readFile(path); String filestr=new String(filebyte,"GBK"); String[] rev=filestr.split("\n"); return rev; } /** * 读文件 * * @param path * 文件名 * @return 文件内容 * @throws IOException */ public static byte[] readFile(String path) throws IOException { return readFile(path, 0); } /** * 读文件 * * @param path * 文件名 * @param offset * 偏移位置 * @return 从偏移位置开始读取的文件内容 * @throws IOException */ public static byte[] readFile(String path, long offset) throws IOException { return readFile(path, offset, -1); } /** * 读文件 * * @param path * 文件名 * @param offset * 偏移位置 * @param size * 读取大小 * @return 从偏移位置开始读取size大小的文件内容 * @throws IOException */ public static byte[] readFile(String path, long offset, int size) throws IOException { InputStream is = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); is = new FileInputStream(path); is.skip(offset); byte[] buff = new byte[4096]; int bufLength = -1; while ((bufLength = is.read(buff)) >= 0) { if (size > 0 && bufLength > size - baos.size()) { baos.write(buff, 0, size - baos.size()); break; } else { baos.write(buff, 0, bufLength); } } return baos.toByteArray(); } finally { if (is != null) { is.close(); } } } /** * 写文件 * * @param path * 文件名 * @param content * 文件内容 * @return 服务端保存文件的实际绝对路径 * @throws IOException */ public static String writeFile(String path, String content) throws IOException { byte[] matter=content.getBytes("GBK"); return writeFile(path, matter, false); } /** * 写文件 * * @param path * 文件名 * @param content * 文件内容 * @param append * 追加方式 * @return 服务端保存文件的实际绝对路径 * @throws IOException */ public static String writeFile(String path, String content,boolean append)throws IOException { byte[] matter=content.getBytes("GBK"); return writeFile(path, matter, append); } public static String writeToFile(String savePath, String content) { File f = new File(savePath); if (f.exists()) f.delete(); try { PrintStream ps = new PrintStream(savePath); String tmp[] = content.split("\n"); for (int i = 0; i < tmp.length; i++) ps.println(tmp[i]); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * 写文件 * * @param path * 文件名 * @param content * 文件内容 * @return 服务端保存文件的实际绝对路径 * @throws IOException */ public static String writeFile(String path, byte[] content) throws IOException { return writeFile(path, content, false); } /** * 写文件 * * @param path * 文件名 * @param content * 文件内容 * @param append * 追加方式 * @return 服务端保存文件的实际绝对路径 * @throws IOException */ public static String writeFile(String path, byte[] content, boolean append) throws IOException { if (path == null || path.length() == 0) { path = File.createTempFile("writeServerFile", ".file") .getAbsolutePath(); } else { path = new File(path).getAbsolutePath(); } OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(path, append)); os.write(content); os.flush(); } finally { if (os != null) { os.close(); } } return path; } /** * 获得该路径下的所有文件名的列表 * @param Url * @return */ public static String[] getFileUrl(String Url) { File path = new File(Url); String[] list; list=path.list(); return list; } } ~~~
';

获取自定义格式的时间

最后更新于:2022-04-01 20:24:43

~~~ import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import cn.com.agree.ab.trade.core.Trade; /** *
*
功能说明
* 字符串处理工具 *
* * @author * @since 2015-6-3 */ public class DateUtil { /** * 功能说明 获取自定义格式的时间 * * @param format * 格式 *

* 例如:
* 使用例子说明 String a=NetCheck.getdataString("yyyyMMdd"); *

*/ public static String getdataString(String format) { DateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(new Date()); } public static String getNextDay(Date date, String format) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, -7); date = calendar.getTime(); DateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(date); } public static String getFormatDate(String datestr) throws ParseException { SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); Date date = null; date = df.parse(datestr); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return dateFormat.format(date); } public static String getNextDay(Date date, String format, int days) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, days); date = calendar.getTime(); DateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(date); } public static List getMonthWeekends(Trade trade,int month,int year) throws IOException{ List hostDays = new ArrayList(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month-1); cal.set(Calendar.DAY_OF_MONTH, 1); int startIndex = cal.get(Calendar.DAY_OF_WEEK) -1 ; // 0~6 表示 周日 ~ 周六 int endIndex = startIndex + getLastDayOfMonth(year, month) - 1; int startday = 1; for (int i = 0; i < 42; i++) { if (i >= startIndex && i <= endIndex) { cal.set(Calendar.DAY_OF_MONTH, startday); if(cal.get(Calendar.DAY_OF_WEEK)==1||cal.get(Calendar.DAY_OF_WEEK)==7){ hostDays.add(startday+""); } startday++; } } return hostDays; } public static boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } public static int getLastDayOfMonth(int year, int month) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } if (month == 2) { if (isLeapYear(year)) { return 29; } else { return 28; } } return 0; } } ~~~
';

前言

最后更新于:2022-04-01 20:24:41

> 原文出处:[Java工具类专栏](http://blog.csdn.net/column/details/java-utility-classes.html) 作者:[hadoop_](http://blog.csdn.net/hadoop_) **本系列文章经作者授权在看云整理发布,未经作者允许,请勿转载!** # Java工具类专栏 > 本人日常工作中写的java实用工具类。
';