這裏是使用時間戳
/*
* created by Sandip Bhoi 9960426568
*/
package checkapplicationisopen;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Random;
public class GeneratorUtil {
/**
*
* @param args
*/
public static void main(String args[])
{
GeneratorUtil generatorUtil=new GeneratorUtil();
generatorUtil.createNewFile("c:\\Documents", "pdf");
}
/**
*
* @param min
* @param max
* @return
*/
public static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
/**
*
* @param prefix adding the prefix for time stamp generated id
* @return the concatenated string with id and prefix
*/
public static String getId(String prefix)
{
java.util.Date date = new java.util.Date();
String timestamp = new Timestamp(date.getTime()).toString();
String dt1 = timestamp.replace('-', '_');
String dt2 = dt1.replace(' ', '_');
String dt3 = dt2.replace(':', '_');
String dt4 = dt3.replace('.', '_');
int temp = randInt(1, 5000);
return prefix +"_"+ temp + "_" + dt4;
}
/**
*
* @param direcotory
* @param extension
*/
public void createNewFile(String direcotory,String extension)
{
try {
File file = new File(direcotory+"//"+getId("File")+"."+extension);
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
'.replace生成文件的代碼(「:」,「」)'的格式字符串時間戳 – Ferrybig
做正確的方式!看看'SimpleDateFormat',它會將你的時間格式化爲一個更靈活的模式,比如''year_month_day_hour_min_sec''格式,沒有任何保留字符。 – MrSimpleMind