Files getting created with old file details in Java - 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

Related

File Writing failed with java.io.FileNotFoundException:

I have a method that returns a TreeMap and trying to write the content from that TreeMap into a file. In Linux, I am trying to create a new file in the dir: /home/sid/AutoFile/ with the current date appended to the file name.
This is what I came up with:
public void createReconFile() throws SQLException, IOException {
Map<String, String> fileInput = new TreeMap<String, String>();
fileInput = getDiffTableCount();
Set<String> countKeys = fileInput.keySet();
Iterator<String> fileInpIter = countKeys.iterator();
Writer output = null;
//creating a file with currentDate
DateFormat df = new SimpleDateFormat("MM/dd/yyyy:HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String reportDate = df.format(today);
System.out.println(reportDate);
try {
File file = new File("/home/sid/AutoFile/" + "count" + reportDate);
output = new BufferedWriter(new FileWriter(file));
System.out.println("Created new file");
while(fileInpIter.hasNext()) {
String tableName = fileInpIter.next();
String cdp = fileInput.get(tableName);
output.write(tableName +" " + cdp+"\n");
}
} catch(IOException e) {
System.out.println("File Writing failed");
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
System.out.println("Closing the file...");
output.close();
}
}
But it ends with the exception:
03/23/2018:05:35:30
File Writing failed
java.io.FileNotFoundException: /home/sid/AutoFile/count03/23/2018:05:35:30 (No such file or directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
The dir: /home/sid/AutoFile/count03/23/2018:05:35:30 is already there and I am trying to create a new file every time that method invokes.
Could anyone let me know what is the mistake I am doing here and how can I create a file properly using java.
Filename in linux cannot have forward slash. So your date format which I believe you want to be used as filename is being taken as directory by linux. You either need to change your date format such that you do not have any forward slash in it or alternatively you can use following line to first create a directory and then write your file in that directory.
new File("/home/ist/" + "count03/23" ).mkdirs();
Also if you already have a directory /home/sid/AutoFile/count03/23/2018:05:35:30 then you cannot have a file with the same name at the same location in linux.

How do I automatically set a directory and create a new file in java?

I made a program for work that can run on multiple pcs. However, the location of the file that is required to run the program(a data file containing employee phone numbers and addresses) is different for each computer. For now I have to compile and save a different version of the program for each user, which takes awhile.
Is there a way for my program to search for the specified file name in the users folder, and or create an empty file automatically if no such file exists yet?
Use below code
public static void main(String[] args) {
try {
String filename = "newFile.txt";
String workingDirectory = System.getProperty("user.dir");
//****************//
File file = new File(workingDirectory, filename);
//****************//
System.out.println("Final filepath : " + file.getAbsolutePath());
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File is already existed!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
For more details go through URL http://www.mkyong.com/java/how-to-construct-a-file-path-in-java/

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

How To Save My Screenshot in 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.

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