take an screenshot and copy that file in my local folder using java io (Webdriver with Java)
File screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("d:\\pic\\report.jpg"));
i call this method more than one time, so in this situation i dont want to repeat the file name as "report.jpg" so please provide an suggestion how can i change that file name dynamically
like
report1
report2 etc.,
A very simple way:
FileUtils.copyFile(screenshot, new File("d:\\pic\\report_" + System.currentTimeMillis() + ".jpg");
I just hope you don't do a screenshot every milliseconds. ;-)
You can improve the readability by using a timestamp.
java.text.SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDD'T'HHMMSSsss");
String newFileName = "d:\\pic\\report_" + sdf.format(new java.util.Date()) + ".jpg";
FileUtils.copyFile(screenshot, newFileName);
Another solution might be to use a static counter in an helper class.
private static int count = 0;
public static void doScreenshot() {
count++;
String newFileName = "d:\\pic\\report_" + count + ".jpg";
FileUtils.copyFile(screenshot, newFileName);
}
You could append the current date and time, or go in a loop checking if the file already exists, appending an number once the file is available.
Date and Time (more meaningful):
Date currDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String dateAndTime = dateFormat.format(currDate);
File reportFile = new File("d:\\pic\\report_" + dateAndTime + ".jpg");
File screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, reportFile));
Number increment method:
File reportFile;
int number = 0;
do {
reportFile = new File("d:\\pic\\report" + number + ".jpg");
number++;
} while (reportFile.exists());
File screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, reportFile));
There are many options.
If the suffix number is important:
Save in a file or in DB the number of times you have generated it
Get the number that contains the name of the last generated file
Count the number of images in the folder (not valid it you delete them after a while)
If it is not important:
Use a datetime with the current time
Use a random number
Related
I read this question here How to create a file in a directory in java?
I have a method that creates a QR Code. The method is called several times, depends on user input.
This is a code snippet:
String filePath = "/Users/Test/qrCODE.png";
int size = 250;
//tbd
String fileType = "png";
File myFile = new File(filePath);
The problem: If the user types "2" then this method will be triggered twice.
As a result, the first qrCODE.png file will be replaced with the second qrCODE.png, so the first one is lost.
How can I generate more than one qr code with different names, like qrCODE.png and qrCODE(2).png
My idea:
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Any tips?
EDIT: I solved it by using a for loop and incrementing the number in the filename in every loop step.
You can create more files eg. like follows
int totalCount = 0; //userinput
String filePath = "/Users/Test/";
String fileName= "qrCODE";
String fileType = "png";
for(int counter = 0; counter < totalCount; counter++){
int size = 250;
//tbd
File myFile = new File(filePath+fileName+counter+"."+fileType);
/*
will result into files qrCODE0.png, qrCODE1.png, etc..
created at the given location
*/
}
Btw to add check if file exists is also good point.
{...}
if(!myFile.exists()){
//file creation
myFile.createNewFile()
}else{
//file already exists
}
{...}
Your idea of solving the problem is a good one. My advice is to break up the filePath variable into a few variables in order to manipulate the file name easier. You can then introduce a fileCounter variable that will store the number of files created and use that variable to manipulate the name of the file.
int fileCounter = 1;
String basePath = "/Users/Test/";
String fileName = "qrCODE";
String fileType = ".png";
String filePath = basePath + fileName + fileType;
File myFile = new File(filePath);
You can then check if the file exists and if it does you just give a new value to the filePath variable and then create the new file
if(myFile.exists()){
filePath = basePath + fileName + "(" + ++fileCounter + ")" + fileType;
myFile = new File(filePath);
}
createFile(myFile);
And you're done!
You can check /Users/Test direcroty before create file.
String dir = "/Users/Test";
String pngFileName = "qrCode";
long count = Files.list(Paths.get(dir)) // get all files from dir
.filter(path -> path.getFileName().toString().startsWith(pngFileName)) // check how many starts with "qrCode"
.count();
pngFileName = pngFileName + "(" + count + ")";
I've tried numerous forms but I'm not getting the size of my photos at all, they're coming out with more than 3mb and I need them to upload numerous pictures via FTP. Follow code for someone could demonstrate a functional gradient
File createImageFile() throws IOException {
Logger.getAnonymousLogger().info("Generating the image - method started");
// New Image
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
String imageFileName = os_id+ "_"+ txtCheckList_id.getText().toString() + "_" + txtCheckListItens_id.getText().toString() + "_1A_" + timeStamp;
File storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "GRP");
Logger.getAnonymousLogger().info("Storage directory set");
if (!storageDirectory.exists()) storageDirectory.mkdir();
File image = new File(storageDirectory, imageFileName + ".png");
Logger.getAnonymousLogger().info("File name and path set");
mImageFileLocation = image.getAbsolutePath();
return image;
}
You can simply use file.length() to get the size of the file, please check the mentioned example,
int file_size = Integer.parseInt(String.valueOf(file.length()/1024));
I would like to know how I can make the program output a new text file every time it runs. For example first run machineslot(1).txt, second run machineslot(2).txt, and so forth. Or, make the output file contain when the file was made.
File file = new File("MachineSlot.Txt");
try(PrintWriter out = new PrintWriter(new FileWriter(file));) {
for (int i = 0; i < winData.length; i++){
if (winData[i][0] != 0.0) {
out.printf("You won Machine %.0f. You won $%.2f. You have %.0f quarters which equals $%.2f %n", winData[i][0], winData[i][1], winData[i][2], winData[i][3]);
}
}
for (int k = 0; k < plays.length; k++)
out.println("You were able to play machine " + (k + 1) +" a total of "+ plays[k] + " times.");
}//end of try.
catch(IOException error){
System.out.println("Could not use the IO file");
}//End catch
My solution to this is use file name and add timestamp to it.
File file = new File("MachineSlot_" + System.currentTimeMillis() + ".txt");
Typically speaking any two files generated will have different time stamp of file generation. Avoid multiple check of existing files.
Other addition is have a formatted date.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS");
File file = new File("MachineSlot_" + formatter.format(new Date()) + ".txt");
You can try this before the PrintWriter code
File file;
int i = 0;
do{
file = new File(String.format("MachineSlot(%d).Txt", i++));
}
while (file.exists());
According to Your problem, best way to add date and time with your file name
String date = new SimpleDateFormat("yyyMMddHHmmssSS").format(new Date());
here current date is converted into specific format then file name would be
File file = new File("MachineSlot" + date + ".txt");
output looks like(file name)-
MachineSlot20171012094424.txt
I have this code here that saves bitmaps of images as a GIF file called test, but everytime the user saves it as test.gif so its constantly overwriting.
What are some ways to avoid overweriting and generate a new filename everytime programmatically?
if(imagesPathList !=null){
if(imagesPathList.size()>1) {
Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "test.gif");
try{
FileOutputStream f = new FileOutputStream(file);
f.write(generateGIF(list));
} catch(Exception e) {
e.printStackTrace();
}
A quick and dirty solution is to put the system time in the filename:
File file = new File(dir, "test_" + System.currentTimeMillis() +".gif");
As long as that method isn't executed at the exact same millisecond, you won't have duplicates.
You can use java.io.File.createTempFile("test", ".gif", dir)
This creates unique filename but they might get significantly long after some time.
Alternatively you can create a method that creates unique filesnames yourself:
private File createNewDestFile(File path, String prefix, String suffix) {
File ret = new File(path, prefix + suffix);
int counter = 0;
while (ret.exists()) {
counter++;
ret = new File(path, prefix + "_" + counter + suffix);
}
return ret;
}
Instead of
File file = new File(dir, "test.gif");
you call
File file = createNewDestFile(dir, "test", ".gif");
This is not thread safe. For that you need a more sophisticated method (e.g. synchronize it and create a FileOutputStream instead of a File which is creating the file already before another call checks of the method checks its existence).
i am creating a file and when i create that file, i check if it already exists. If it already exists, i want to create it with the same name, but with the (1) after it. I am able to do that and here is the code :
File apkReceived = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + ".apk");
if(apkReceived.exists()){
apkReceived=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + "(1)"+".apk");
}
byte[] buffer = new byte [8192];
FileOutputStream fos=new FileOutputStream(apkReceived);
then it would continue... (i am writing things on the file).
This works but the problem is that in this situation :
FileTest.apk
FileTest(1).apk
If I receive another Filetest, it will sub my FileTest(1), since it will create it again.
A solution for this would be to check if the file exists again, but then i would have to be doing that for ever.
My goal would be to create (1) and then (2) , etc.
Does any one of you know how to do this ?
EDIT: Obviously i could use a cicle to check it. The problem is on how to get the (1) and then the (2) and don't get the (1)(2)
To avoid reinventing the wheel I suggest using Timestamp it hardly ever will have collisions.
java.util.Date date= new java.util.Date();
Timestamp tstamp = new Timestamp(date.getTime());
File apkReceived = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + tstamp + ".apk");
Do Something like this
File apkReceived = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + ".apk");
if(apkReceived.exists()){
int new_int_postfix;
//Below _MAX is max numbers of file eg. _MAX = 100
for(int i = 1; i < _MAX; i++) {
apkReceived = = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName +"("+ i +")"+".apk");
if(!apkReceived.exists()) {
String []name_without_pre = receivedApkName.split("\\(");
receivedApkName = name_without_pre[0];
new_int_postfix = i;
break;
}
}
apkReceived = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + "("+new_int_postfix+")"+".apk");
}
byte[] buffer = new byte [8192];
FileOutputStream fos=new FileOutputStream(apkReceived);
Some pseudocode to get you started:
Fetch a list of all files in the directory
For the one you want to copy: check if you already have one or more copies
If you already have "file_(n)"; use "file_(n+1)" as new filename.
Obviously: you should clarify your requirements on the "maximum" n you want to allow; and what to happen when n copies were created; and another is asked for.
If you only store that one type of file in your directory you can do:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
count the size and size + 1 for your next filename.
you can also separate each file with similiar filename on their own directory.
try this
String filename =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/"+receivedApkName + ".apk";
File f = new File(filename);
String extension = ".apk";
int g = 0;
while(f.exists()) {
int i = f.lastIndexOf('.');
if (i > 0)
{ extension = fileName.substring(i+1); }
f.renameTo(f.getPath() + "\" + (f.getName() + g) + "." + extension)
}