有时候我们需要截图,在要截图时,有人用到了时间格式,但是时间格式中的:在文件名称中是不被允许的字符,所以就会报错,如何生成唯一的时间文件名:
package com.demo; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class TimeString { private String valueOfString(String str, int len) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < len - str.length(); i++) { sb.append("0"); } return (sb.length() == 0) ? (str) : (sb.toString() + str); } public String getDateFormat(){ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.format(new Date()); } public Date getDateFormat(String time){ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { return df.parse(time); } catch (ParseException e) { e.printStackTrace(); } return null; } private String getTimeString(Calendar calendar) { StringBuffer sb = new StringBuffer(); sb.append(String.valueOf(calendar.get(Calendar.YEAR))) .append(this.valueOfString(String.valueOf(calendar.get(Calendar.MONTH) + 1),2)) .append(this.valueOfString(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)),2)) .append(this.valueOfString(String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)),2)) .append(this.valueOfString(String.valueOf(calendar.get(Calendar.MINUTE)),2)) .append(this.valueOfString(String.valueOf(calendar.get(Calendar.SECOND)),2)) .append(this.valueOfString(String.valueOf(calendar.get(Calendar.MILLISECOND)),3)); return sb.toString(); } public String getTimeString(String time){ Calendar calendar = new GregorianCalendar(); calendar.setTime(this.getDateFormat(time)); return this.getTimeString(calendar); } public String getTimeString(){ Calendar calendar = new GregorianCalendar(); return this.getTimeString(calendar); } public static void main(String[] args) { TimeString ts = new TimeString(); System.out.println(ts.getTimeString()); System.out.println(ts.getTimeString("2015-4-30 8:51:52")); } }
虽然上面的getTimeString方法精确到了毫秒,但仍会有可能产生相同的文件名,导致覆盖,所以,在生成文件名时判断一下是否存在:
package com.demo; import java.io.File; public class Test16 { public String getFileName(String path){ File file = new File(path); if(file.exists()){ return this.getFileName(file.getParent()+File.separator+(new TimeString().getTimeString())+".png"); } return path; } public static void main(String[] args) { Test16 t = new Test16(); System.out.println(t.getFileName("D:/1.txt")); } }
理论上来说,这种也是有可能产生相同的文件名的,这种在多线程中是有可能的,解决的办法很简单,自已想去!