Current timestamp as filename in Java

前端 未结 7 1550

I want to name new files created by my Java application with the current timestamp.

I need help with this. How do I name the new files created with the current timestamp

7条回答
  •  野的像风
    2021-02-03 18:08

    Improving the @Derek Springer post with fill length function:

    public static String getFileWithDate(String fileName, String fileSaperator, String dateFormat) {
        String FileNamePrefix = fileName.substring(0, fileName.lastIndexOf(fileSaperator));
        String FileNameSuffix = fileName.substring(fileName.lastIndexOf(fileSaperator)+1, fileName.length());
        //System.out.println("File= Prefix~Suffix:"+FileNamePrefix +"~"+FileNameSuffix);
        
        String newFileName = new SimpleDateFormat("'"+FileNamePrefix+"_'"+dateFormat+"'"+fileSaperator+FileNameSuffix+"'").format(new Date());
        System.out.println("New File:"+newFileName);
        return newFileName;
    }
    

    Using the funciton and its Output:

    String fileSaperator = ".", format = "yyyyMMMdd_HHmm";
    getFileWithDate("Text1.txt", fileSaperator, format);
    getFileWithDate("Text1.doc", fileSaperator, format);
    getFileWithDate("Text1.txt.json", fileSaperator, format);
    

    Output:

    Old File:Text1.txt   New File:Text1_2020Nov11_1807.txt
    Old File:Text1.doc   New File:Text1_2020Nov11_1807.doc
    Old File:Text1.txt.json  New File:Text1.txt_2020Nov11_1807.json
    

提交回复
热议问题