Java, Create file name using data and time

datefilejavatime

I'm trying to create a file name that uses the date and time from another class to name it, problem is the class is called every so often and when it is a new file is created. I just wanted to create the file once and then write to it all the time. Is it possible to do this as I can't work out how to?

Many thanks for any help in advance!

public void fileOutputToFile(String hex) throws Exception{

    dateAndTime dat = new dateAndTime();
    String date = dat.currentDateAndTime();

    String fileInfo = hex;
    String fileName = (date+".tsv");

    try{
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
        out.print(fileInfo);
        out.print("\t");
        out.close();
    }catch (IOException e){
    }
}

Best Solution

Use a date formatter like SimpleDateFormat to format the date to a string, e.g. "yyyy" to make a file 2011.tsv. Note that this requires a Date object to be returned.

If you don't want to use a file based on date, store the filename somewhere. But why would you then use the date as the filename in the first place?

Edit: For a new file every hour, use a format like this: yyyy-MM-dd_HH (would result in 2011-03-29_17.tsv for example).