在开发当中一些封装好的方法可以提高开发效率,在此记录一些开发当中常用的方法,如果有好用的方法,在这里会不断的更新~
生成任意位数的随机字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
public static String getRandStr(int length) { Random random = new Random(); String sRand = ""; for (int i = 0; i < length; i++) { String indexStr = String.valueOf(random.nextInt(61)); int index = Integer.valueOf(indexStr); String rand = chars[index]; sRand += rand; } return sRand; }
|
随机生成4位或者6位数字
1 2 3 4 5 6 7 8 9 10 11
|
public static String randomNum(int length) { if (length == 4) { return toString((int) ((Math.random() * 9 + 1) * 1000)); } else { return toString((int) ((Math.random() * 9 + 1) * 100000)); } }
|
生成任意位的随机数
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
public static String getNum(int length) { Random rd = new Random(); String[] radmon = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { String s = radmon[rd.nextInt(10)]; sb.append(s); } return sb.toString(); }
|
格式化评论时间
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 26 27 28 29 30 31 32 33 34 35
|
public static String formatCommentDate(Date date) { Date nowDate = new Date(); long min = 60 * 1000L; long hour = 60 * 60 * 1000L; long day = 60 * 60 * 1000 * 24L; long day5 = 60 * 60 * 1000 * 24 * 5L; long time = (nowDate.getTime() - date.getTime()); SimpleDateFormat format = new SimpleDateFormat("MM-dd"); String str = ""; if (min > time) { str = "刚刚"; } else if (hour > time) { str = time / min + "分钟前"; } else if (day > time) { str = time / hour + "小时前"; } else if (day5 > time) { str = time / day + "天前"; } else if (day5 < time) { str = format.format(date); } return str; }
|
将手机号替换成133****1234
1 2 3 4 5 6 7 8 9 10
|
public static String replaceMobile(String mobile, String regex) { String rep = mobile.substring(3, 7); mobile = mobile.replaceAll(rep, regex); return mobile; }
|
创建二维码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
public static void createQr(int width, int height, String filePath, String content, String format) throws Exception { Map map = Maps.newHashMap(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); map.put(EncodeHintType.MARGIN, 2); BitMatrix bitMatrix = new MultiFormatWriter() .encode(content, BarcodeFormat.QR_CODE, width, height); Path file = new File(filePath).toPath(); MatrixToImageWriter.writeToPath(bitMatrix, format, file); }
|