Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20



Create File with Time Stamp in Java

In some occasions, you need to include time stamp in the file or directory name. See the example below. 


package com.seleniummaster.examplefile;

import java.text.SimpleDateFormat;
import java.util.Date;

public class CreateFileWithTimeStamp {

    public static void main(String[] args)

    //Create a new file
    public static void CreateFileWithTimeStamp(String filename) {
        //get current project path
        String filePath = System.getProperty("user.dir");
        //create a new file with Time Stamp
        File file = new File(filePath + "\\" + filename+GetCurrentTimeStamp().replace(":","_").replace(".","_")+".txt");

        try {
            if (!file.exists()) {
                System.out.println("File is created; file name is " + file.getName());
            } else {
                System.out.println("File already exist");
        } catch (IOException e) {
        // Get current system time
    public static String GetCurrentTimeStamp() {
        SimpleDateFormat sdfDate = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss.SSS");// dd/MM/yyyy
        Date now = new Date();
        String strDate = sdfDate.format(now);
        return strDate;
    // Get Current Host Name
    public static String GetCurrentTestHostName() throws UnknownHostException {
        InetAddress localMachine = InetAddress.getLocalHost();
        String hostName = localMachine.getHostName();
        return hostName;

    // Get Current User Name
    public static String GetCurrentTestUserName() {
        return System.getProperty("");


Run the code and see the result. A text file with time stamp is created.

File is created; file name is test2015-05-05 22_27_29_684.txt