Setting file creation timestamp in Java
Asked Answered
F

4

28

I know setting the creation timestamp doesn't exist in Java because Linux doesn't have it, but is there a way to set a file's (Windows) creation timestamp in Java? I have a basic modification timestamp editor I made right here.

import java.io.*;
import java.util.*;
import java.text.*;
import javax.swing.*;

public class chdt{
    static File file;
    static JFrame frame = new JFrame("Input a file to change");
    public static void main(String[] args) {
        try{

            final JFileChooser fc = new JFileChooser();
            fc.setMultiSelectionEnabled(false);

            //BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            //System.out.println("Enter file name with extension:");
            //String str = bf.readLine();
            JOptionPane.showMessageDialog(null, "Input a file to change.");
            frame.setSize(300, 200);

            frame.setVisible(true);

            int retVal = fc.showOpenDialog(frame);
            if (retVal == JFileChooser.APPROVE_OPTION) {
                file = fc.getSelectedFile();
                frame.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(null, "3RR0RZ!  You didn't input a file.");
                System.exit(0);
            }

            //System.out.println("Enter last modified date in 'dd-mm-yyyy-hh-mm-ss' format:");
            //String strDate = bf.readLine();
            String strDate = JOptionPane.showInputDialog("Enter last modified date in 'dd-mm-yyyy-hh-mm-ss' format:");

            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
            Date date = sdf.parse(strDate);

            if (file.exists()){
                file.setLastModified(date.getTime());
                JOptionPane.showMessageDialog(null, "Modification is successful!");
            }
            else{
                JOptionPane.showMessageDialog(null, "File does not exist!  Did you accidentally it or what?");
            }
        }
        catch(Exception e){
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "3RR0RZ");
        }
    }
}
Foin answered 8/2, 2012 at 17:14 Comment(0)
S
2

I believe you have the following options:

  1. Find a tool that does this and is callable from the command line. Then you can interact with it from your java code.
  2. The following link from MSDN File Times shows how any tool would be doing it - especially note the functions GetFileTime and SetFileTime.

And here I guess you will be lucky :) Searching for those functions on Google I found a post here on SO. This answer (not the accepted one) to How to Discover a File's Creation Time with Java seems to do exactly what you want using JNA and the methods above. And if it does, then please upvote that answer one more time :)

Please don't mind the title it has a method to set the creation time too. I hope you will manage to get it working.

Semblance answered 8/2, 2012 at 18:9 Comment(0)
K
43

Here is how you do it in Java 7 with the nio framework:

public void setFileCreationDate(String filePath, Date creationDate) throws IOException{

    BasicFileAttributeView attributes = Files.getFileAttributeView(Paths.get(filePath), BasicFileAttributeView.class);
    FileTime time = FileTime.fromMillis(creationDate.getTime());
    attributes.setTimes(time, time, time);

}

the BasicFileAttributeView.setTimes(FileTime, FileTime, FileTime) method arguments set the last modified time, last accessed time, and creation time respectively.

Kirk answered 12/2, 2015 at 18:25 Comment(2)
Hmm does this allow setting the last modified time < (earlier) than the creation time ? ???Sarcenet
set creation time not work on macOS, see bugs.openjdk.java.net/browse/JDK-8151430Classmate
R
25

Starting from Java 7, you can use java.nio.file.Files.setAttribute and the creationTime attribute:

Path p = Paths.get("C:\\Users\\first.last\\test.txt");
try {
    Calendar c = Calendar.getInstance();
    c.set(2010, Calendar.MARCH, 20);
    Files.setAttribute(p, "creationTime", FileTime.fromMillis(c.getTimeInMillis()));
} catch (IOException e) {
    System.err.println("Cannot change the creation time. " + e);
}

Other attributes can be found here:

Name                  Type
-------------------------------
"lastModifiedTime"    FileTime
"lastAccessTime"      FileTime
"creationTime"        FileTime
"size"                Long
"isRegularFile"       Boolean
"isDirectory"         Boolean
"isSymbolicLink"      Boolean
"isOther"             Boolean
"fileKey"             Object
Ronrona answered 3/6, 2016 at 15:28 Comment(5)
Unfortunately, setting the creation time fails silently on some Unixes (e.g. OS X, even though it should be supported on HFS). If you want to be sure that it was actually set, read after you wrote and check!Dever
For me it failed silently on Linux with ext3 and ext4, because these FS just do not support creationDates. Reading the creationDate in Java will return the lastModifiedDate!Speechmaking
Does not work with Linux.Formula
@admins how is this is not the accepted answer?Caaba
@Formula which is a definition gap in POSIX baeldung.com/linux/get-file-creation-dateCaaba
S
2

I believe you have the following options:

  1. Find a tool that does this and is callable from the command line. Then you can interact with it from your java code.
  2. The following link from MSDN File Times shows how any tool would be doing it - especially note the functions GetFileTime and SetFileTime.

And here I guess you will be lucky :) Searching for those functions on Google I found a post here on SO. This answer (not the accepted one) to How to Discover a File's Creation Time with Java seems to do exactly what you want using JNA and the methods above. And if it does, then please upvote that answer one more time :)

Please don't mind the title it has a method to set the creation time too. I hope you will manage to get it working.

Semblance answered 8/2, 2012 at 18:9 Comment(0)
G
-4

You should search for java.nio if you are using jdk >= 1.7

You can also try this (worked well for me on Macos Mavericks and get me two different timestamps):

file.setLastModified(created.getTime()); //Older Timestamp
file.setLastModified(updated.getTime()); //Newer Timestamp
Goosefish answered 7/3, 2014 at 12:21 Comment(1)
How does this set the file creation time?Unpack

© 2022 - 2024 — McMap. All rights reserved.