java如何随机生成定长的字符串

小数,字符串、时间等示例代码

String base = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
public class RandomTest {

    public static Random rand = new Random();
    public static String dateStart = "2017-01-01 00:00:00";
    /**
     * hh 表示12小时制
     * HH 表示24小时制
     */
    public static SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
    public static SimpleDateFormat format1 = new SimpleDateFormat("YYYYMMDDHHmmss");


    public static void main(String[] args) throws ParseException {
        System.out.println(getDouble());

        long timeStart = 1483200000000l;
        System.out.println(format.parse(dateStart).getTime());

        System.out.println(format.format(new Date(timeStart)));
        System.out.println(format.format(new Date(timeStart+1000)));
        System.out.println(format.format(new Date(timeStart+2000)));

        format.format(new Date());

        System.out.println(getRandomString(2));

    }
    /**
     * 随机生成指定精确度的小数
     * @return
     */
    public static double getDouble(){
        DecimalFormat df=new DecimalFormat("#.000000");
        int a=(int)(Math.random()*2+1);
        int aa=(int)(Math.pow(-1, a));

        return Double.valueOf(df.format(rand.nextDouble()*100*aa));
    }
    /**
     * 生成固长字符串
     * @param length
     * @return
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";   
        Random random = new Random();   
        StringBuffer sb = new StringBuffer();   
        for (int i = 0; i < length; i++) {   
            int number = random.nextInt(base.length());   
            sb.append(base.charAt(number));   
        }   
        return sb.toString();   
     }  
    /**
     * 生成固长字符串
     * @param length
     * @return
     */
    public static String getRandomStringNum(int length) { //length表示生成字符串的长度
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
        Random random = new Random();   
        StringBuffer sb = new StringBuffer();   
        for (int i = 0; i < length; i++) {   
            int number = random.nextInt(base.length());   
            sb.append(base.charAt(number));   
        }   
        return sb.toString();   
    }
}

--------------------- 本文来自 AngelaPotato 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/wangxilong1991/article/details/72636482?utm_source=copy 

posted on 2018-09-26 11:14  小甜瓜安东泥  阅读(1397)  评论(0编辑  收藏  举报