Vasanthan
Vasanthan

Reputation: 13

timestamp as file name in java

I need to create a text file in the name of current timestamp in a particular directory

D:\Assignments\abassign in java.

But when i try to do that the following error comes as the file name should not contain ':'. But the timestamp contains ':'

Exception in thread "main" java.io.IOException: The filename, directory name, or volume label syntax is incorrect at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:883) at abassign.Abassign.main(Abassign.java:35) Java Result: 1

This error shows up

Upvotes: 0

Views: 2437

Answers (3)

Sandip Bhoi
Sandip Bhoi

Reputation: 470

here is the Code to generate file using time stamp

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

}

Upvotes: 0

Laszlo Merczel
Laszlo Merczel

Reputation: 96

I use something like this:

    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();

(Of course, you can drop the prefix, postfix and workingDirectory parts)

Upvotes: 2

Guillaume Barré
Guillaume Barré

Reputation: 4218

If you are on Windows your file name cannot contain :, you need to replace it by another character...

The following characters are reserved :

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

For example :

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

Upvotes: 1

Related Questions