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

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

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

Can't make Files and Folders

So i'm working on a simple Windows Explorer replacement. I want to add the ability to create Folders and Files. For some reason, it only works when i'm in my root or c:/ folder, but as soon as it's somewhere else (for example C:\Program Files (x86)) it doesn't work. I either get a java.io.IOException: Access Denied when i create a File and when i try to create a folder, no Exception comes up, but no folder is created.
This is my code for a new file:
String location = getPath();
String name = JOptionPane.showInputDialog("Fill in the name of the new file. \nDon't forget to add file type (.txt, .pdf).", null);
if(name == null){
}
else {
File newFile = new File(location + "\\" + name);
boolean flag = false;
try {
flag = newFile.createNewFile();
} catch (IOException Io) {
JFrame messageDialog = new JFrame("Error!");
JOptionPane.showMessageDialog(messageDialog, "File creation failed with the following reason: \n" + Io);
}
}
This is my code for a new Folder:
String location = getPath();
String name = JOptionPane.showInputDialog("Fill in the name of the new folder.", null);
if(name == null){
}
else {
File newFolder = new File(location + "\\" + name);
boolean flag = false;
try {
flag = newFolder.mkdir();
} catch (SecurityException Se) {
JFrame messageDialog = new JFrame("Error!");
JOptionPane.showMessageDialog(messageDialog, "Folder creation failed with the following reason: \n" + Se);
}
}
I'm stuck right now and i have no idea what i'm doing wrong to get rid of the access denied error.
Short explenation of how this program works:
My program shows a list of all folders and files from a selected File.
That File is a field in the class JXploreFile called "currentFile", which behaves almost the same as a File.
When browsing through the folders, the currentFile is set to a new JXploreFile, containing the new folder you are in as File.
When creating a new folder/file, my program ask the path the user is currently browsing in with the method getPath().
Thanks for the help!
Image of my program:
Before you try to make any I/O operation just check if you have the permission
go to the parent directory (your case location)
then do something like
File f = new File(location);
if(f.canWrite()) {
/*your full folder creation code here */
} else {
}
try to put
String location ="c:\\user\<<youruser>>\\my documents"
or a folder with full perission to write

Download entire FTP directory in Java (Apache Net Commons)

I am trying to recursively iterate through the entire root directory that I arrive at after login to the FTP server.
I am able to connect, all I really want to do from there is recurse through the entire structure and and download each file and folder and have it in the same structure as it is on the FTP. What I have so far is a working download method, it goes to the server and gets my entire structure of files, which is brilliant, except it fails on the first attempt, then works the second time around. The error I get is as follows:
java.io.FileNotFoundException: output-directory\test\testFile.png
(The system cannot find the path specified)
I managed to do upload functionality of a directory that I have locally, but can't quite get downloading to work, after numerous attempts I really need some help.
public static void download(String filename, String base)
{
File basedir = new File(base);
basedir.mkdirs();
try
{
FTPFile[] ftpFiles = ftpClient.listFiles();
for (FTPFile file : ftpFiles)
{
if (!file.getName().equals(".") && !file.getName().equals("..")) {
// If Dealing with a directory, change to it and call the function again
if (file.isDirectory())
{
// Change working Directory to this directory.
ftpClient.changeWorkingDirectory(file.getName());
// Recursive call to this method.
download(ftpClient.printWorkingDirectory(), base);
// Create the directory locally - in the right place
File newDir = new File (base + "/" + ftpClient.printWorkingDirectory());
newDir.mkdirs();
// Come back out to the parent level.
ftpClient.changeToParentDirectory();
}
else
{
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
String remoteFile1 = ftpClient.printWorkingDirectory() + "/" + file.getName();
File downloadFile1 = new File(base + "/" + ftpClient.printWorkingDirectory() + "/" + file.getName());
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
}
}
}
}
catch(IOException ex)
{
System.out.println(ex);
}
}
Your problem (well, your current problem after we got rid of the . and .. and you got past the binary issue) is that you are doing the recursion step before calling newDir.mkdirs().
So suppose you have a tree like
.
..
someDir
.
..
someFile.txt
someOtherDir
.
..
someOtherFile.png
What you do is skip the dot files, see that someDir is a directory, then immediately go inside it, skip its dot files, and see someFile.txt, and process it. You have not created someDir locally as yet, so you get an exception.
Your exception handler does not stop execution, so control goes back to the upper level of the recursion. At this point it creates the directory.
So next time you run your program, the local someDir directory is already created from the previous run, and you see no problem.
Basically, you should change your code to:
if (file.isDirectory())
{
// Change working Directory to this directory.
ftpClient.changeWorkingDirectory(file.getName());
// Create the directory locally - in the right place
File newDir = new File (base + "/" + ftpClient.printWorkingDirectory());
newDir.mkdirs();
// Recursive call to this method.
download(ftpClient.printWorkingDirectory(), base);
// Come back out to the parent level.
ftpClient.changeToParentDirectory();
}
A complete standalone code to download all files recursively from an FTP folder:
private static void downloadFolder(
FTPClient ftpClient, String remotePath, String localPath) throws IOException
{
System.out.println("Downloading folder " + remotePath + " to " + localPath);
FTPFile[] remoteFiles = ftpClient.listFiles(remotePath);
for (FTPFile remoteFile : remoteFiles)
{
if (!remoteFile.getName().equals(".") && !remoteFile.getName().equals(".."))
{
String remoteFilePath = remotePath + "/" + remoteFile.getName();
String localFilePath = localPath + "/" + remoteFile.getName();
if (remoteFile.isDirectory())
{
new File(localFilePath).mkdirs();
downloadFolder(ftpClient, remoteFilePath, localFilePath);
}
else
{
System.out.println("Downloading file " + remoteFilePath + " to " +
localFilePath);
OutputStream outputStream =
new BufferedOutputStream(new FileOutputStream(localFilePath));
if (!ftpClient.retrieveFile(remoteFilePath, outputStream))
{
System.out.println("Failed to download file " + remoteFilePath);
}
outputStream.close();
}
}
}
}

Get character from string between similar sings

I am trying to get a path of an image in my android device, such as:
/ storage/emulated/0/DCIM/Camera/NAME.jpg
and just trying to grab the image name, but i can.
I am trying with ...
String s = imagePath;
Where the route imagePath
            
s = s.substring (s.indexOf ("/") + 1);
s.substring s = (0, s.indexOf () ".");
Log.e ("image name", s);
it returns me :
storage/emulated/0/DCIM/Camera/NAME.jpg
and i only want
NAME.jpg
You need String.lastIndexOf():
String imagePath = "/path/to/file/here/file.jpg";
String path = imagePath.substring(imagePath.lastIndexOf('/') + 1);
You can do something like that:
File imgFile = new File(imagePath);
String filename = imgFile.getFilename();
This saves you a lot of hassle when you want to use your application cross-platform, because on Linux you have "/" as path delimiters and "\" on Windows
In case, if you are dealing with File object, then you can use its predefined method getName().
i.e.:
File mFile = new File("path of file");
String filename = mFile.getName();

Trying to get file paths to work across all releases in Java/Netbeans

So I'm working on a game, and I need help with my file i/o for savefiles. Currently I have something like this setup to read from them:
public static void savesManagementMenu() {
for (int i = 1; i < 4; i++) {
fileURL = JRPG.class.getResource("Saves/save" + i + ".txt");
System.out.println(fileURL);
if (fileURL != null) {
saveMenuSaveFile = new File(fileURL.getPath());
try {
//System.out.println("File # " + i +" exists.");
saveMenuSaveFileReader = new FileReader(fileURL.getPath());
saveMenuFileScanner = new Scanner(saveMenuSaveFileReader);
saveMenuInfo[i - 1][0] = saveMenuFileScanner.nextLine();
saveMenuFileScanner.nextLine();
saveMenuFileScanner.nextLine();
saveMenuFileScanner.nextLine();
saveMenuInfo[i - 1][1] = saveMenuFileScanner.nextLine();
saveMenuInfo[i - 1][2] = saveMenuFileScanner.nextLine();
} catch (FileNotFoundException ex) {
Logger.getLogger(JRPG.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
saveMenuInfo[i - 1][0] = null;
}
}...
And running/compiling using this method from Netbeans will make the application/game look in "E:\Copy\JRPG\build\classes\jrpg\Saves."
When I clean and build the project, and try to run it via the command line I get a response like this:
jar:file:/C:/Users/Adam/Desktop/New%20folder/JRPG.jar!/jrpg/Saves/save1.txt
Aug 22, 2013 11:54:18 PM jrpg.JRPG savesManagementMenu
SEVERE: null
java.io.FileNotFoundException: file:\C:\Users\Adam\Desktop\New%20folder\JRPG.jar
!\jrpg\Saves\save1.txt (The filename, directory name, or volume label syntax is
incorrect)
And the game just freezes up. The file path for the saves that I want it to look into when I run the compiled code is: C:\Users\Adam\Desktop\New folder\Saves
Which would be the relative file path right? How can I fix this problem so that my compiled code looks in the correct location no matter where I run the file from? (Lets say my friend wanted to run the game from his computer except he put the "New Folder" folder somwhere other than his desktop)
A embedded resource is not a File and can't be treated as one. Also, as far as output files, you shouldn't be trying to save inside your application anyway...
Instead, either save the file to the relative location of your application...
File saveMenuSaveFile = new File("./Saves/save" + i + ".txt");
Or to the users home directory...
String userHome = System.getProperty("user.home");
File saveMenuSaveFile = new File(userHome + "/.YouApplicationName/Saves/save" + i + ".txt");

Categories

Resources