使用日期和时间创建文件名

时间:2011-03-09 07:05:16

标签: java datetime filenames

我希望你能帮助我,我试图在另一个班级打电话,看起来像“2011-03-09 06-57-40”,我想用这个来创建下面的文件,但每次都是我在输出运行时执行它创建一个新文件,因为它重新运行调用dat()。我知道出了什么问题我只是不确定如何修复它,我想要写一个同样的文件。我希望这是有道理的? :/

提前感谢您提供任何帮助:)

    date d = new date();
    String  cdate = d.date();


    String f = h;

    try{
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(cdate + ".tsv", true)));
        out.print(f);
        out.print("\t");
        out.close();
    }catch (IOException e){
    }

5 个答案:

答案 0 :(得分:35)

创建名为当前日期/时间的文件:

Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ;
File file = new File(dateFormat.format(date) + ".tsv") ;
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("Writing to file");
out.close();

答案 1 :(得分:18)

这个可能要容易得多。只有一行代码可以将文件名称指定为日期和时间。

String out = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss'.tsv'").format(new Date());

答案 2 :(得分:10)

我会尝试回答所有问题。要以最可控的方式获取日期或时间字符串,请使用以下代码

Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = dateFormat.format(cal.getTime());

查找http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html。它可能有助于理解。您还可以为格式化的字符串添加小时/分钟或所需内容。

另一种选择可能是始终将日历中的“较低”字段(如毫秒,秒,分钟)设置为零。

cal.set(Calendar.MINUTE,0);

如果您要从其他课程中检索日期而无法直接创建日历,您也可以将日期放入日历中(注意:只需格式化您不需要日历)

cal.setTime(date);

这可能有助于更好地控制创建的文件名/文件。

答案 3 :(得分:2)

它会更高效 - 每个文件只有一个SimpleDateFormat和Date对象,以及没有字符串连接。

private  final static String getDateTime()  
{  
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");  
    df.setTimeZone(TimeZone.getTimeZone("PST"));  
    return df.format(new Date());  
}  

答案 4 :(得分:1)

public class BELogs {

    private final static Logger logger = Logger.getLogger(BSELogs.class
            .getName()); 

             boolean makeDir = false;
             Date date = new Date();
             SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy") ;
             String curDate =dateFormat.format(date);
             FileHandler fh;     

               public BSELogs()  {

         try {  

             File file = new File("/home//Desktop/Logs "+curDate);
             makeDir = file.mkdir();
             fh = new FileHandler(file+"/MyLogFile.log "+curDate,true);  
             logger.addHandler(fh);
             // Set the logger level to produce logs at this level and above.
             logger.setLevel(Level.FINE);
             SimpleFormatter formatter = new SimpleFormatter();  
             fh.setFormatter(formatter);  

          } catch (SecurityException ex) {  **strong text**
             ex.printStackTrace();  
          } catch (IOException e) {  
               e.printStackTrace();  
           }  

    logger.info("Data Log Genrated............"); 

      }
}