How to append date and time in multiple file in a folder while moving it to another folder - java

public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
Source Folder
File source = new File("D:\\A1\\");
File dest = new File("D:\\A2\\");
File[] files = source.listFiles();
for (File file: source.listFiles()){
String x=(source+"\\"+file.getName());
String y=(dest + "\\"+ file.getName());
File f1 = new File(x);
f1.renameTo(new File(y));
}
This code is moving the file from source to destination folder but i want when file moved to destination folder . it appends the the system date with its name
Please Help

You need to append the timestamp to the filename, at best right before the extension.
Note that operating systems may not allow some characters to appear in a filename, for example the colon and the slash may not be use on windows, so yo need to find a substitue for them.
Also you need to check the return value of renameTo to check whether the file was realy moved or not.
returns true if and only if the renaming succeeded; false otherwise
You could try something like this:
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String ts = dateFormat.format(date);
File source = new File("D:\\A1\\");
File dest = new File("D:\\A2\\");
for (File file : source.listFiles()) {
String x = (source + "\\" + file.getName());
String y = (dest + "\\" + addTimestamp(file.getName(), ts));
File f1 = new File(x);
if(f1.renameTo(new File(y))){
System.out.println("moved: " + y);
} else {
System.out.println("unable to move: " + y);
}
}
}
private static String addTimestamp(String name, String ts) {
int lastIndexOf = name.lastIndexOf('.');
return (lastIndexOf == -1 ?
name + "_" + ts
:
name.substring(0, lastIndexOf) + "_" + ts +
name.substring(lastIndexOf))
.replaceAll("[\\/:\\*\\?\"<>| ]", "_");
}
Finally for moving files better use Files#move as the javadoc of renameTo itself suggests.

You can do it this way
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
Date date = new Date();
y=(dest + "\\"+ file.getName()+dateFormat.format(date));

As per Java Docs of File#renameTo method, it is a platform dependent implementation and it may not work as you expect.
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
Note that the Files class defines the move method to move or rename a
file in a platform independent manner.
You can alternatively use Files#move method. It is a Platform Independent method.
Hope this helps

Related

Creating a new folder each time Selenium WebDriver takes a screenshot

// Take screenshot method
static void captureScreenshot(String fileName) throws IOException {
// Take the screenshot and store as file format
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Open the current date and time
String timestamp = new SimpleDateFormat("dd_MM_yyyy__hh_mm_ss").format(new Date());
//Copy the screenshot on the desire location with different name using current date and time
Cache.copyFile(scrFile, new File("C:\\Users\\Kiko Kikostov\\IdeaProjects\\AboutPagesBanerScreenSizes\\15inchScreenSize\\Asia\\" + fileName + " " + timestamp + ".png"));
String st = scrFile.getAbsolutePath();
String str = scrFile.getParent();
scrFile = new File(str+"/"+ "/" + fileName);
}
This works fine for me but I want to implement that every time the test is run a new folder or subfolder is created inside the existing one.
You can create a directory with the os
import os
directory = "MyFolder"
parent_dir = "D:/Pycharm projects/"
path = os.path.join(parent_dir, directory)
os.mkdir(path)
print("Directory '% s' created" % directory)
So, for your usecase should be something like this:
import os
parent_dir="C:\\Users\\Kiko Kikostov\\IdeaProjects\\AboutPagesBanerScreenSizes\\15inchScreenSize\\Asia\\";
// Take screenshot method
static void captureScreenshot(String fileName) throws IOException {
// Take the screenshot and store as file format
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Open the current date and time
String timestamp = new SimpleDateFormat("dd_MM_yyyy__hh_mm_ss").format(new Date());
// Assuming you want a folder with the timestamp
directory = timestamp;
path = os.path.join(parent_dir, directory)
os.mkdir(path)
//Copy the screenshot on the desire location with different name using current date and time
Cache.copyFile(scrFile, new File(directory + fileName + " " + timestamp + ".png"));
String st = scrFile.getAbsolutePath();
String str = scrFile.getParent();
scrFile = new File(str+"/"+ "/" + fileName);

Naming a text file with a date and time parameter + a string

in my project I have to encrypt some notes of patients what i do is I get the "LocalDateTime dateTime" through a parameter and create a file with that name + "Encryptedtxt" + ".txt". And additionally I wanted to add the doctors id too but first of all I need to do the first part. So i attempted the task but it's not working as I'm expecting. This is the part where I'm creating the file,
public void txtEncrypt(String text, LocalDateTime localDateTime) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
try {
String subfolder = "Encryption" + File.separator + "txt";
String fileName = localDateTime + "-encryptedText.txt";
File file = new File(subfolder, fileName);
FileOutputStream outStream = new FileOutputStream(file);
This only works partially. This is the output
This only adds the localDate time ". -encryptedText.txt" is missing.
Can someone kindly help me out in this one?
you can't use local date time object directly in file name, it will give you text value like - 2023-01-07T14:38:00.502959700 so you can't create file name with colon(:) in it.
You need to format your local date time object in any permissible format then it will work. You can try below code -
String subfolder = "Encryption" + File.separator + "txt";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmmss");
String fileName = localDateTime.format(formatter) + "-encryptedText.txt";
File file = new File(subfolder, fileName);
FileOutputStream outStream = new FileOutputStream(file);
I think you should call dateFormat.format(localDateTime), or something like that, and get an string to add to the "-encryptedText.txt", to sum up, you need to add an string to another string, you can not add a string to an object
HH:mm:ss is invaild for filename,so this filename is filtered

Cannot create file with Java using the Parent and Child parameters of the new File constructor

I am trying to create a file using Java. I want to create this file in a sub-folder of my "Documents" directory. I want this sub-folder to be based today's date.
I thought I new how to use the File class and file.mkdirs() method properly, but I guess I don't.
Here is what I have:
public class FileTest {
private static final String sdfTimestampFormat = "yyyy-MM-dd HH:mm:ss Z";
private static final SimpleDateFormat timestampSDF = new SimpleDateFormat(sdfTimestampFormat);
private static final String sdfDirFormat = "yyyy-MM-dd";
private static final SimpleDateFormat dirSDF = new SimpleDateFormat(sdfDirFormat);
public static void test() throws FileNotFoundException, IOException{
Date rightNow = new Date();
String data = "the quick brown fox jumps over the lazy dog";
String path = System.getProperty("user.home");
String filename = "file.txt";
String directory_name = path + System.getProperty("file.separator") + "Documents" + System.getProperty("file.separator") + dirSDF.format(rightNow);
File file = new File(directory_name, filename);
if(file.mkdirs()){
String outstring = timestampSDF.format(rightNow) + " | " + data + System.getProperty("line.separator");
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(outstring.getBytes());
fos.close();
}
}
}
What is happening is that the following directory is created:
C:\Users\<username>\Documents\2018-08-03\file.txt\
I was under the impression that the Parent parameter of the new File constructor was the base directory, and the Child paramater of the new File constructor was the file itself.
Is this not the case? Do I need two File objects, one for the base directory and another for the file?
What I want is this:
C:\Users\<username>\Documents\2018-08-03\file.txt
Thanks.
mkdirs() will do directories (if they don't exist) for each element in your path.
So you can use file.getParentFile().mkdirs() to not make a directory for your file.txt
Edit: Something to consider
mkdirs() only returns true if it actually created directories. If they already existed or there was a problem creating them it will return false
Since you are trying to run this multiple times to append to your text your logic will not run inside your if-statement
I would change it to:
boolean created = true;
if(!file.getParentFile().exists()) {
created = file.getParentFile().mkdirs();
}
if (created) {
String outstring = timestampSDF.format(rightNow) + " | " + data + System.getProperty("line.separator");
FileOutputStream fos = new FileOutputStream(file, true);
fos.write(outstring.getBytes());
fos.close();
}

Hard coding part of the Path in Java

I have the following dir tree
C:\folder1\folder2\SPECIALFolders1\folder3\file1.img
C:\folder1\folder2\SPECIALFolders2\folder3\file2.img
C:\folder1\folder2\SPECIALFolders3\folder3\file3.img
C:\folder1\folder2\SPECIALFolders4\folder3\file4.img
C:\folder1\folder2\SPECIALFolders5\folder3\file5.img
I want to get to folder2, list all dirs in it (SpecialFolders) then retrieve the paths of those folders while adding (folder3) to their path
The reason I'm doing this is I want later to pass this path (paths) to a method to retrieve last modified files in folder3. I know there are way easier ways to do it but this is a very particular case.
I'm also trying to retrieve those folders within a specific time range so I used a while loop for that
Date first = dateFormat.parse("2015-6-4");
Calendar ystr = Calendar.getInstance();
ystr.setTime(first);
Date d = dateFormat.parse("2015-6-1");
Calendar last = Calendar.getInstance();
last.setTime(d);
while(last.before(ystr))
{
//fullPath here = "C:\folder1\folder2\"
File dir = (new File(fullPath));
File[] files = dir.listFiles();
for (File file : files)
{
//Retrieve Directories only (skip files)
if (file.isDirectory())
{
fullPath = file.getPath();
//last.add(Calendar.DATE, 1);
System.out.println("Loop " + fullPath);
}
}
}
fullPath += "\\folder3\\";
return fullPath;
The problem with my code is that it only returns one path (that's the last one in the loop) --which make sense but I want to return all of the paths like this
C:\folder1\folder2\SPECIALFolders1\folder3\
C:\folder1\folder2\SPECIALFolders2\folder3\
C:\folder1\folder2\SPECIALFolders3\folder3\
C:\folder1\folder2\SPECIALFolders4\folder3\
C:\folder1\folder2\SPECIALFolders5\folder3\
I appreciate your input in advance
Instead of fullPath String, use for example ArrayList<String> to store all paths. Than instead of:
fullPath = file.getPath();
use:
yourArrayList.add(file.getPath());
Your method will return an ArrayList with all paths, and you will need to code a method to retrive all paths from it.

Writing to a text file by a method that takes in a string parameter

Hi guys, I'm trying to pass in a string parameter to write that string to a text file.
However , I seem to be having trouble. It works fine when I compile it in a main method, it creates a file and all the values that I write into it.
However, when I use a method. It doesn't create a file at all, not even with the parameters that i passed in. I am intending to use the method in a servlet.
Below is the method that I created.
public class testWriteFile {
public static void writeToFile (String data) throws Exception {
Date dateNow = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
StringBuilder formatDDMMYYYY = new StringBuilder(sdf.format(dateNow));
File file = new File(formatDDMMYYYY+".txt");
if(!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
System.out.println("Done");
}
}
May I know what is the problem with the code?
Thanks in advance!
Finally, seems like the issue was resolved when the OP printed
System.out.println(file.getCanonicalPath());
It was in a different directory since the OP was using an IDE.
use a full path ("d:/myfolder/a.txt") - can still keep part of it dynamic like if windows
File f = new File("D:/myfolder/" + formatDDMMYYYY + ".txt");
Or linux/ mac
File f = new File("/myfolder/" + formatDDMMYYYY + ".txt");
Make sure you have write permission on the myfolder and replace it with one you do have by using touch command on linux/ unix like systems in terminal :
touch /myfolder/a.txt
ls -l /myfolder/a.txt
Should show current date for that file

Categories

Resources