Reputation: 71
Can someone show me an example code of how to create new text file using date and time as text file name. Please show also how to save that new text file in a specific folder path in computer. I try this but its not working
File f = new File("D://FILEPATH//Clear.DAT");
String fileName = f.getName();
fileName = fileName+new java.util.Date() +".DAT";
System.out.println(fileName);
Upvotes: 2
Views: 2975
Reputation: 103
Here is one more way i used with Java8
String dateTime= DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(ZonedDateTime.now());
String fileName = String.format("Clear-%s.DAT", dateTime);
Path filePath = FileSystems.getDefault().getPath("D://FILEPATH//", fileName);
Files.createFile(filePath);
Upvotes: 0
Reputation: 201439
First, get the date and time as a String
formatted correctly. You can use SimpleDateFormat
. And you can use the File(File, String)
constructor to give your File
the correct folder. Then you might use a PrintStream(File)
to print
something. And a try-with-resources
Statement to clean-up. Finally, you could put that all together into something like
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
File folder = new File("D://FILEPATH");
File f = new File(folder, String.format("Clear-%s.TXT", df.format(new Date())));
try (PrintStream ps = new PrintStream(f) {
ps.println("Hello, File!");
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 3
Reputation: 593
Date date = new Date() ;
SimpleDateFormat dateObject = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ;
File yourTextFile = new File(dateObject.format(date) + ".tsv") ;
BufferedWriter result = new BufferedWriter(new FileWriter(yourTextFile));
result.write("Writing content");
out.close();
Try with above code. It will create a file with the current date and time.
Upvotes: 0
Reputation: 574
Try to create file name with date from the very beginning. Plus, it would be great to choose date and time format that you are going to use.
Upvotes: 0