【问题标题】:timestamp as file name in javajava中的时间戳作为文件名
【发布时间】:2016-04-13 11:02:23
【问题描述】:

我需要在特定目录中以当前时间戳的名称创建一个文本文件

D:\Assignments\abassign 在java中。

但是当我尝试这样做时,会出现以下错误,因为文件名不应包含“:”。但时间戳包含':'

线程“main”java.io.IOException 中的异常:文件名、目录名或卷标语法不正确 在 java.io.WinNTFileSystem.createFileExclusively(本机方法) 在 java.io.File.createNewFile(File.java:883) 在 abassign.Abassign.main(Abassign.java:35) Java 结果:1

出现此错误

【问题讨论】:

  • .replace(":", ".") 上的字符串格式时间戳
  • 以正确的方式做事!看看SimpleDateFormat,它将把你的时间格式化成更灵活的模式,比如"year_month_day_hour_min_sec"格式,没有任何保留字符。

标签: java sql timestamp


【解决方案1】:

我使用这样的东西:

    StringBuffer fn = new StringBuffer();
    fn.append(workingDirectory);
    fn.append("/");
    fn.append("fileNamePrefix-");
    fn.append("-");
    DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss");
    fn.append(df.format(new Date()));
    fn.append("-fileNamePostFix.txt");
    return fn.toString();

(当然可以去掉前缀、后缀和workingDirectory部分)

【讨论】:

    【解决方案2】:

    如果您在 Windows 上,您的文件名不能包含 :,您需要将其替换为另一个字符...

    以下字符被保留:

    < (less than)
    > (greater than)
    : (colon)
    " (double quote)
    / (forward slash)
    \ (backslash)
    | (vertical bar or pipe)
    ? (question mark)
    * (asterisk)
    

    例如:

    String yourTimeStamp = "01-01-2016 17:00:00";
    File yourFile = new File("your directory", yourTimeStamp.replace(":", "_"));
    

    【讨论】:

      【解决方案3】:

      这是使用时间戳生成文件的代码

      /*
       * 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();
                  }
              }
      
      }
      

      【讨论】:

      • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
      猜你喜欢
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 2010-11-07
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多