QA's approach 2 Java - File Creation with Date and Time

File Creation in java Example


package fileHandling;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class CreateFile {

/**
* @param args
* @throws ClassNotFoundException
*/
public static void main(String... args) throws ClassNotFoundException {
String fileName = null;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the file name to create");
fileName = sc.next();
String filePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "fileHandling"
+ File.separator + fileName + "_" + GetCurrentTimeStamp().replace(":", "_").replace(".", "_") + ".txt";
// System.out.println(filePath);

File createNew = null;
try {
createNew = new File(filePath);

// returns true if new file is created else is file already exists
// returns false
boolean b = createNew.createNewFile();

if (b)
System.out.println("File with name:" + fileName + " Created successfully");
else
System.out.println("File to be created already exists with the same name");

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

// Get current system time
public static String GetCurrentTimeStamp() {
  DateFormat format = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
//Used to format Date to text format
// Date now=new Date(); String timeStamp = format.format(new Date()); return timeStamp;

}

}

Comments

Popular posts from this blog

QA's approach 2 Java - Understanding Static context

Selenium 4 absolute beginners - How to create Batch execution file

Technologies - Log4J - Create Log4j Configuration File - Where ? How ? What ?