当前位置: 移动技术网 > IT编程>开发语言>Java > java利用时间格式生成唯一文件名的方法

java利用时间格式生成唯一文件名的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

前言

有时候我们需要截图,在要截图时,有人用到了时间格式,但是时间格式中的:在文件名称中是不被允许的字符,所以就会报错,如何生成唯一的时间文件名:

示例代码

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"));
  }
 
}

理论上来说,这种也是有可能产生相同的文件名的,这种在多线程中是有可能的,解决的办法很简单,自已动脑筋想想想去吧!

总结

以上就是关于java中通过时间格式来生成唯一文件名的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网