package com.gx.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
public class RandomUtils {
private static SimpleDateFormat format1=new SimpleDateFormat("yyyyMMddHHmmssSSS");
private static SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
private static Random random = new Random();
/**
* 使用时间+四位随机数
* @param oldName a.sd.df.ds.jpg
*/
public static String createRandomFileNameUseTime(String oldName) {
//得到文件名的最后一点的下标
int lastDotIndex=oldName.lastIndexOf(".");
//从lastDotIndex截取到oldName.length
String suffix = oldName.substring(lastDotIndex,oldName.length());
//生成时间字符串
String timeStr = format1.format(new Date());
//生成四位随机数
int random4Num = random.nextInt(9000)+1000;
return timeStr+random4Num+suffix;
}
public static void main(String[] args) {
String createRandomFileNameUseTime = createRandomFileNameUseTime("a.sd.df.ds.jpg");
String createRandomFileNameUseUuid = createRandomFileNameUseUuid("a.sd.df.ds.jpg");
String createRandomFileNameUseGNTime = createRandomFileNameUseGNTime("a.sd.df.ds.jpg");
System.out.println(createRandomFileNameUseTime);
System.out.println(createRandomFileNameUseUuid);
System.out.println(createRandomFileNameUseGNTime);
}
/**
* 使用uuid
*/
public static String createRandomFileNameUseUuid(String oldName) {
//得到文件名的最后一点的下标
int lastDotIndex=oldName.lastIndexOf(".");
//从lastDotIndex截取到oldName.length
String suffix = oldName.substring(lastDotIndex,oldName.length());
//生成uuid字符串
String uuid = UUID.randomUUID().toString().replace("-", "");
return uuid+suffix;
}
/**
* 使用格林毫秒+四位随机数
*/
public static String createRandomFileNameUseGNTime(String oldName) {
//得到文件名的最后一点的下标
int lastDotIndex=oldName.lastIndexOf(".");
//从lastDotIndex截取到oldName.length
String suffix = oldName.substring(lastDotIndex,oldName.length());
//生成时间字符串
long time = System.currentTimeMillis();
//生成四位随机数
int random4Num = random.nextInt(9000)+1000;
return time+random4Num+suffix;
}
/**
* 得到当前上期下的日期 去生成文件夹名
* @return
*/
public static String getCurrentDateToStr() {
return sdf2.format(new Date());
}
}