How To Save My Screenshot in java - java

I'm making a program that takes a screenshot and I want to have it so that i have a JButton with an actionlistener that when pressed it saves the image to a certain folder that if does not already exists it makes.
here is what I thought I should do:
#Override
public void actionPerformed(ActionEvent arg0) {
File dir = new File("C://SnippingTool+/" + date.getDay());
dir.mkdirs();
try {
ImageIO.write(shot, "JPG", dir);
} catch (IOException e) {
e.printStackTrace();
}
}
});
I think it has something to do with my File dir = new File and that I am not saving to to the right place.
Here is my Robot taking a screenshot:
try {
shot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
} catch (HeadlessException e1) {
e1.printStackTrace();
} catch (AWTException e1) {
e1.printStackTrace();
}

The problem, as I see it is with these two lines...
File dir = new File("C://SnippingTool+/" + date.getDay());
dir.mkdirs();
This now means that the output you are trying to write to is a directory, when ImageIO is expecting a file, this will fail...
Instead try something like...
File output = new File("C://SnippingTool+/" + date.getDay() + ".jpg");
File dir = output.getParentFile();
if (dir.exists() || dir.mkdirs()) {
try {
ImageIO.write(shot, "JPG", output);
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Bad Path - " + dir);
}

In response to your comment:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at main$2$2.actionPerformed(main.java:148)
That is at the:
File output = new File(System.getProperty("user.home") +
date.getDay() + ".jpg");
(I changed the "C:\" to System.getProperty("User.home")).
There are only two possible causes of an NPE in that line (wrapped for readability):
If System.getProperty cannot find the named property, it will return a null. Now the "user.home" property should exist ... but "User.home" almost certainly does NOT exist. (Property names are case sensitive!!)
If date is null or date.getDay() returns null. We don't know how you initialized date ... or even what type it is. (Though Date would be a good guess ...)
Both the "user.home" property and the "user.dir" property would work ... though they mean different things.

Related

Files getting created with old file details in Java

I am trying to create a simple program which checks if a file was created older than today and delete that file to create a new one . But the creatNewFile method is recreating the file with the old (deleted) files properties . For example the new file also has a creation date of yesterday .
What am i doing wrong here ?
private File createFile() {
logger.trace("Entering createFile method ");
File trackerFile = new File("tracker.txt");
if (!trackerFile.exists()) {
try {
logger.debug("File does not exist . New file being created ");
trackerFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String dateCreated = df.format(this.getCreationTime(trackerFile).toMillis());
logger.debug("File exists file creation time is {}" , dateCreated);
Calendar currCalendar = Calendar.getInstance();
Calendar fileCreateCalendar = Calendar.getInstance();
fileCreateCalendar.setTime(df.parse(dateCreated));
if (currCalendar.get(Calendar.DAY_OF_MONTH) > fileCreateCalendar.get(Calendar.DAY_OF_MONTH)) {
logger.debug("File exists file not created today , being deleted");
trackerFile.delete();
trackerFile.createNewFile();
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
logger.trace("Exiting createFile method ");
return trackerFile;
}
Please check out this simple code snippet .. the file is created , deleted and then recreated . The file created at the end has a creation date which is the same as the first file that was deleted . How does this happen ?
public class CreateTempFile {
public static void main(String[] args) {
try {
File file = new File("test.txt");
file.createNewFile();
file.delete();
File newFile = new File("test.txt");
newFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I would suggest you to use similar code to get date / time in order to be sure that you are retrieving the right value (e.g. creation is not modification etc):
Path file = "tracker.txt";
BasicFileAttributes fileAttributes = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + fileAttributes.creationTime());
System.out.println("lastAccessTime: " + fileAttributes.lastAccessTime());
System.out.println("lastModifiedTime: " + fileAttributes.lastModifiedTime());
You can find more details in the reference here:
https://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html
I found the answer in an older post , the link is given below .
After deleting file and re-creating file, not change creation date in windows

Load multiple images with different paths

so i try to load two images from the same path but with different names.
if i copy the path directly from the image everything work fine.
but if i try to build the path from the system only one of them work(img1).
i've try couple of different ways i found in the internet to build the path but the results are the same.
what can cause this problem?
public void loadImages(String nm) {
File f = null;
BufferedImage image = null;
System.out.println("read img:");
String pathName = PICTURE_PATH + this.getMyColor().toString().toLowerCase() + nm;
// read successful this img path.
try {
f = new File(pathName + "North.png");
f.canRead();
System.out.println("\nimg1 path:" + f);
System.out.print("img1 absolute path:" + f.getAbsolutePath());
img1 = ImageIO.read(f);
if (!f.canRead())
throw new IOException("Cant read the first file");
if (!f.exists())
throw new IOException("Cant find the first file");
System.out.println("Successful read img 1");
} catch (IOException e) {
System.out.println("Error:" + e);
}
// got here exception error for this img path.
try {
f = new File(pathName + "East.png");
System.out.println("\nimg2 path:" + f);
System.out.println("img2 absolute path:" + f.getAbsolutePath());
if (!f.canRead())
throw new IOException("Cant read the second file");
if (!f.exists())
throw new IOException("Cant find the second file");
img2 = ImageIO.read(f);
System.out.println("Successful read img 2");
} catch (IOException e) {
System.out.println("Error:" + e);
}
System.out.println("Done.");
}
//this is the relevant output for this function:
//read img:
img1 path:src\icons\‏‏silverCarNorth.png
img1 absolute path:A:\Tools\eclipse\WorkPlace\HW1\src\icons\‏‏silverCarNorth.png
Successful read img 1
img2 path:src\icons\‏‏silverCarEast.png
img2 absolute path:A:\Tools\eclipse\WorkPlace\HW1\src\icons\‏‏silverCarEast.png
Error:java.io.IOException: Cant read the second file
Done.
so its appear the images had some extra characters..
the site not support this kind of characters so i add a print screen from the cmd.
this is the logs from the cmd:
cmd logs
so i had to rename the files and delete the extra characters manually with the windows command line.
and after that everything works just fine!

Java FileNotFoundExeception not working

In my current project I am having an issue with not receiving a file not found exception. My driver file passes the path to be opened to the constructor that is building a library of books. I am using JFileChooser to get the path. In trying to force an error (entering the name of a file that does not exist), it builds the library with no information in it, and does not throw an error.
Driver Code:
//open an existing library
JFileChooser dlg = new JFileChooser ("LibraryData");
FileNameExtensionFilter filter = new FileNameExtensionFilter ("Text Files", "txt");
dlg.setFileFilter(filter);
dlg.setDialogTitle("Select Existing File");
dlg.setApproveButtonToolTipText("Select the file you want to open and click me.");
int button = dlg.showOpenDialog(null);
if (button == dlg.APPROVE_OPTION)
{
currentPath = dlg.getSelectedFile().getPath();
library = new PersonalLibrary(currentPath);
System.out.println("===========================================================");
System.out.println("File opened successfully from: \n" + currentPath);
System.out.println("===========================================================");
}
Util.enterToContinue();
Util.clearScreen();
break;
Library Code:
public PersonalLibrary(String path)
{
try
{
File myFile = new File(path);
if (myFile.exists())
{
Scanner input = new Scanner(myFile);
while(input.hasNext())
{
//code that populates the library
}
input.close();
saveNeeded = false;
}
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
Your checking if the file exists the catch block will never be executed.
if(myFile.exists())
If it doesn't exist nothing else will be executed including catch block. FileNotFoundException could not occur in this block of code. If you want to catch FileNotFoundException get rid of the if block. Or just add an else block and do you processing there whatever processing you want to do when a file doesn't exist.
the method File#exists() checks if a file is existing or not. If it does, it returns true and goes into your if block.
Since the file is not there, it just simply skips the if block and moves on. Since no attempt was made to access a non-existing file object, the exception is not thrown.
If you would like to throw an exception, you have to do so yourself like this,
if(file.exists()) {
//do file operation
} else {
throw new FileNotFoundException("Oops! No file...");
}

java.io.file backslash saving in weblogic's root

I have a java application running into a weblogic server.
The application have to write a file into the path \bla\john doe (for example).
For this, I used the java.io.File library to:
1. Verify if the path exists
2. If not, create it.
3. Verify if the file exists
4. if not, create it
5. Write the bytes into the file.
The correct behavior would be to create the directory bla into the root of the weblogic's current domain and then create a john doe inside it.
The problem is: in my current enviroment it works like a charm, but in the client's one, the application does not consider the backslash as an element of the path, and instead of creating two directories, the application only creates one, literally named as \bla\john does.
So, instead of:
-domain_root
-bla
-john does
I get the following:
-domain_root
-\bla\john does
(and if I escape it, occurres the same but with two backslash)
The odd is that if I use the commom slash (/bla/john doe), it works..
-domain_root
-bla
-john does
Does any one knows what possibly can be happening?
script for check the path
public File checkPath(String path) {
File f = new File(cls_Util.NeutralizeFilePath(path));
if (!(f.exists() && f.isDirectory())) {
try {
f.mkdirs();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return f;
}
script for check the file:
public File checkFile(String path){
File f = new File(path);
return checkFile(f);
}
public File checkFile(File f) {
if (!(f.exists() && f.isFile())) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return f;
}
script for create file
public File writeFile(String path, byte[] binaryfile) {
File file = checkFile(path);
if (file != null) {
FileOutputStream fos;
try {
fos = new FileOutputStream(path);
try {
fos.write(binaryfile);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return file;
}
return null;
}
And to create the file:
String filePathPub = pathPub + newName;
File FilePathPub = writeFile(filePathPub, p_Arquivo);
On Windows the \ starts an absolute path; on Unix/Linux the backslash is a valid filename character (and therefore starts a relative path).
I would suggest you try to avoid using file name concatenation platform specific separators if you are not familiar with the semantic:
File current = new File();
File bla = new File(current, "bla");
(or simply stick to / (forward slash as used by Unix) to separate path components). Java translates this to the Windows character automatically).

Overwriting txt file in java

The code I've written is supposed to overwrite over the contents of the selected text file, but it's appending it. What am I doing wrong exactly?
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
f2 = new FileWriter(fnew,false);
f2.write(source);
/*for (int i=0; i<source.length();i++)
{
if(source.charAt(i)=='\n')
f2.append(System.getProperty("line.separator"));
f2.append(source.charAt(i));
}*/
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT
I tried making a new temp.txt file and writing the new contents into that, deleting this text file and renaming temp.txt to this one. Thing is, the deletion is always unsuccessful. I don't think I have to change user permissions for this do I?
Also, a part of my program lists all the files in this directory, so I'm guessing they're being used by the program and so can't be deleted. But why not overwritten?
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold=new File("../playlist/"+existingPlaylist.getText()+".txt");
fold.delete();
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
Your code works fine for me. It replaced the text in the file as expected and didn't append.
If you wanted to append, you set the second parameter in
new FileWriter(fnew,false);
to true;
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
Add one more line after initializing file object
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();
This simplifies it a bit and it behaves as you want it.
FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");
try {
f.write(source);
...
} catch(...) {
} finally {
//close it here
}
The easiest way to overwrite a text file is to use a public static field.
this will overwrite the file every time because your only using false the
first time through.`
public static boolean appendFile;
Use it to allow only one time through the write sequence for the append field
of the write code to be false.
// use your field before processing the write code
appendFile = False;
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
//change this line to read this
// f2 = new FileWriter(fnew,false);
// to read this
f2 = new FileWriter(fnew,appendFile); // important part
f2.write(source);
// change field back to true so the rest of the new data will
// append to the new file.
appendFile = true;
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories