Creating a new folder each time Selenium WebDriver takes a screenshot - java

// 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);

Related

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();
}

How to change the path to get screenshots to a folder named time stamp?

I have taken screen shots of appium test with following script.
String path;
try {
WebDriver augmentedDriver = new Augmenter().augment(driver);
File source = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
path = "/Users/admin/Desktop/newfolder" + source.getName();
org.apache.commons.io.FileUtils.copyFile(source, new File(path));
}
catch(IOException e) {
path = "Failed to capture screenshot: " + e.getMessage();
}
I want to take them to a folder named with timestamp.
But now I'm getting them to desktop named like this
How to give path to a folder to save these screen shots during appium test?
Try this to create folder with timestamp name:
String.valueOf(new Timestamp(System.currentTimeMillis())).replace(":", "-")
Add a "/" after "newfolder" when you set path = to make it
path = "/Users/admin/Desktop/newfolder/" + source.getName();
Taking The N…'s answer into account, the path should be created like:
String timestampAsString = String.valueOf(new Timestamp(System.currentTimeMillis())).replace(":", "-");
path = "/Users/admin/Desktop/" + timestampAsString + "/" + source.getName();

Error while creating directory to store file

I need help to store new folders created according to the current time. After adding the codes for the time, I have received error stating that the system cannot find the path specified.
Here's my current code:
public void fileCreation( String fileData ) throws IOException
{
String nameOfFile = "c:\\Shane\\Work\\Desktop\\Storage_" + Config.retrieveDate + "\\" + this.nameOfFile + ".csv";
FileWriter writeFile = new FileWriter (nameofFile);
writeFile.append( fileData );
writeFile.flush();
writeFile.close();
}
My Config file has the current line of code:
public static String retrieveDate = "";
And declaration at another file:
Config.retrieveDate = sdf.format(new Date());
Output should be: e.g. ( Storage_20150416082500 ) -YYYYMMDDHHMMSS format.
Edit
Error occured:
java.io.FileNotFoundException: c:\Shane\Work\Desktop\Storage_2015041061404210\Type A.csv (Access is denied)
at test.DataGetter.fileCreation(Retrieval.java:55)
It looks like the directory c:\Shane\Work\Desktop\Storage_20150416082500 doesn't exist when you first try to create a file to it.
If that's the case, you should first check if the directory exists and if not, create it. Only then can you create a file within it:
public void fileCreation(String fileData ) throws IOException {
String dirName = "c:\\Shane\\Work\\Desktop\\Storage_" + Config.retrieveDate + "\\";
File dir = new File(dirName);
if (!dir.exists())
dir.mkdir();
//directory definitely exists here, we can create a file to it:
String nameOfFile = dirName + this.nameOfFile + ".csv";
FileWriter writeFile = new FileWriter (nameofFile);
writeFile.append( fileData );
writeFile.flush();
writeFile.close();
}
Of course for that to work, the parent directory (c:\Shane\Work\Desktop) would have to exist in the first place.
If you are going to access an existing file its a good practice to always Try checking if the file really exist or not , you can achieve it by
File file=new File(pathToYourFile.extension);
if(file.exists()){
// do whatever you want to do
}
else{
//either throw any exception or create that file manually if required
}
Make sure the directories you are trying to create the file in are present, if not present, create.
public void fileCreation( String fileData ) throws IOException {
String nameOfFile = "c:\\Shane\\Work\\Desktop\\Storage_" + Config.retrieveDate + "\\" + this.nameOfFile + ".csv";
// Make directories if not present
new File(nameOfFile).getParentFile().mkdirs();
FileWriter writeFile = new FileWriter (nameofFile);
writeFile.append( fileData );
writeFile.flush();
writeFile.close();
}

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

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

Categories

Resources