Adding Time to an Image - java

I'm trying to take a screenshot using the following code
public void TakeScreenShot() {
String ScreenPrefix = "Screenshot-";
String Time = getTime();
try {
File ScreenName = new File(ScreenPrefix+Time+".png");
BufferedImage image = new Robot().createScreenCapture(new Rectangle(getGameScreen()));
ImageIO.write(image, "PNG", new File(System.getProperty("user.home") + "\\Desktop\\ScreenShots\\"+ScreenName));
JOptionPane.showMessageDialog(null, ScreenName+".png has been saved to your desktop", "Console", JOptionPane.PLAIN_MESSAGE);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if I use the getTime(); method I get the following error:
java.io.FileNotFoundException: C:\Users\Evan\Desktop\ScreenShots\Screenshot-19:30:14 (The filename, directory name, or volume label syntax is incorrect)
but if I change
File ScreenName = new File(ScreenPrefix+Time);
to
File ScreenName = new File(ScreenPrefix);
It works perfectly fine, it just doesn't include the time the screenshot was taken.
if anyone knows how to make the code create the file "Screenshot-Hour:Minute:Seconds"
and is willing to share, it would be very apprieciated
(if you can tell me why I'm getting this error it'd be quite helpful as well)
If you need it, here's my getTime() method:
public static String GetTime() {
Calendar cal = Calendar.getInstance();
cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(cal.getTime());
}
I do have the path "C:\Users\Evan\Desktop\Screenshots" as well, so I don't know why it's telling me I don't when I try to include the time, because it works fine without it

You need to edit the name of the file being saved such that it does not include special characters.
That error is saying the file you're trying to create is invalid.

Related

Android Changing The Modified Date For Files Exported To Local Storage

I am creating an android app and added an option to save media such as images and videos, I need to be able to change the modified date of the file to whatever the current date and time are. I have been using the File method to save files. I have seen that this is a known issue with the .setLastModified() method in Android but am unable to find any other solution to this problem. This method doesn't seem to do anything at least on my device (Google Pixel 2). It will just have the original date.
I have even tried doing some "dirty method" by using the RandomFileAccess() method (I'll show the code below) But with no luck.
File rootPath = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "imageAlbum");
if(!rootPath.exists()) {
rootPath.mkdirs();
}
File localFile = new File(rootPath,filename.toLowerCase());
Then I use firebase and the .getFile() method.
This is what I mean by a "dirty" method.
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(rootPath + "/" + finalFilename.toLowerCase(), "rw");
long length = raf.length();
raf.setLength(length + 1);
raf.setLength(length);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
localFile.setLastModified(System.currentTimeMillis());
But again with no luck.
EDIT:
Here is the code I am using for firebase.
String finalFilename = filename;
storageReference.getFile(localFile).addOnCompleteListener(new OnCompleteListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<FileDownloadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
localFile.setLastModified(System.currentTimeMillis());
{
I have tried using the ".setLastModified" method before and after calling the firebase methods.

Content provider with internal storage

I'm writing an app in which I'm saving photos in internal storage. I'm using solution from this blog
I know names of two files before, so I can have in a code, but in my app there will be also a gallery. So my question is: how to save files without knowing their name(file name is generated using date and time)? Content provider's oncreate starts during initialisation so how to pass new files names to content provider?
Thanks in advance.
In the content provider class remove in onCreate the file creation completely.
public static String lastPictureSaved = "";
Change the function openFile. There the filename will be made accordig to date time and the file created.
Date date = new Date();
date.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
String datetimestr = formatter.format(date);
lastPictureSaved = getContext().getFilesDir() + "/" + datetimestr + ".jpg";
File f = new File(lastPictureSaved);
try
{
f.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
Log.d(TAG, e.getMessage());
}
in the Host activity change
File out = new File(getFilesDir(), "newImage.jpg");
to
File out = new File(MyFileContentProvider.lastPictureSaved);

How to take screenshot of Current window or simulate print screen using selenium web drivver

I am creating an automation tool , which will help in taking screen shot of the web page , I m using Selenium Web driver (Java) , Currently I m able to take screen shot of the entire web page with the following code
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("full.jpeg"));
But I want to take screen shot of the current window alone (I want to simulate the action of print screen function) using selenium , kindly guide me , on how to take screen-shot of the current web page alone .Thanks in Advance
Regards,
Vignesh
Have a look at my utility code
public static String captureScreen() {
//get your driver instance
try {
File source = ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy/MMM/dd HH:mm:ss");
String dateN = formatter.format(currentDate.getTime()).replace("/","_");
String dateNow = dateN.replace(":","_");
String snapShotDirectory = /*your snapshot folder path*/+ dateNow;
File f = new File(snapShotDirectory);
if(f.mkdir()){
path = f.getAbsolutePath() + "/" + source.getName();
FileUtils.copyFile(source, new File(path));
}
}
catch(IOException e) {
path = "Failed to capture screenshot: " + e.getMessage();
}
return path;
}
just call this method wherever you want to take snapshots.
There is nothing in WebDriver that supports this, but you can take a screenshot using Java Robots:
http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html#createScreenCapture%28java.awt.Rectangle%29

Duplicate files using java timestamp naming

I have an application that merges two audio files into a single one.
My problem is, that when I run the application, sometimes (haven't been able to find out exactly when) I get the same file duplicated with two different names. When the output should be just 1 file
Here's the code I'm using to name the files:
AudioInputStream audioInputStream = null;
audioInputStream = new MixingFloatAudioInputStream(audioFormat, audioInputStreamList);
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
String strOutputFilename = timeStamp + "-" + tel +".wav";
System.out.println("Llamadas/" + strOutputFilename);
File outputFile = new File("Llamadas/" + strOutputFilename);
try
{
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, outputFile);
}
catch (IOException e)
{
e.printStackTrace();
}
It doesn't throws any kind of error, I just get the duplicates with a difference on their names of 1 second on their tampstamp part.
ie:
20130910134003-097496427.wav
20130910134004-097496427.wav
Any idea of the reason or another method to get always the right timestamp?

File Directory and File Creation Problems

I have problems with the following code. I am trying to look at an existing directory to see if a file exists before creating a new one, but it doesnt seem to create a new file even though there are no existing ones in the directory. I have attached the two relevant methods, but the problem lies with the writeFile() method. I tried to use the existing 'dir' in writeFile, this didnt do the trick either. The rest of the program does seem to work, just the writeFile method has problems.
public void writeFile(String t) throws IOException {
File temp1 = new File(dateNow + File.separator + "Temperature.txt");
boolean check = temp1.exists();
if (!check)
newFiles();
}
public void newFiles() {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
dateNow = formatter.format(now.getTime());
System.out.println(dateNow);
// if (hour == 00 && mini == 00 && sec == 00) {
try {
dir = new File(dateNow);
boolean x = dir.mkdir();
// ....
} catch (Exception e) {
//
}
}
you need to specify the full path, not just the directory and the file name to create a file or even check it's existence,.
thank you for michael667, you remind me about the relative position is right,. :)
and there should be no problem with the above code,.

Categories

Resources