<p>Is there an easy way to discover a File's creation time with Java?  The File class only has a method to get the "last modified" time.  According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time.</p>

<p>The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time.  I guess this works, I only need to support Windows, but it seems very error prone to me.</p>

<p>Are there any third party libraries that provide the info I need?</p>

<p><strong>Update:</strong> In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a  good choice for anyone else that has this problem. </p>

[{'answer_id': 32712, 'author': 'Joseph Gordon', 'author_id': 1741, 'author_profile': 'https://Stackoverflow.com/users/1741', 'pm_score': 1, 'selected': False, 'text': '<p>I like the answer on <a href="http://www.jguru.com/faq/view.jsp?EID=1297118" rel="nofollow noreferrer">jGuru</a> that lists the option of using <a href="http://en.wikipedia.org/wiki/Java_Native_Interface" rel="nofollow noreferrer">JNI</a> to get the answer. This might prove to be faster than shelling out and you may encounter other situations such as this that need to be implemented specifically for windows.</p>\n\n<p>Also, if you ever need to port to a different platform, then you can port your library as well and just have it return -1 for the answer to this question on *ix.</p>\n'}, {'answer_id': 2193954, 'author': 'Kothar', 'author_id': 37416, 'author_profile': 'https://Stackoverflow.com/users/37416', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve been investigating this myself, but I need something that will work across Windows/*nix platforms.</p>\n\n<p>One SO post includes some links to <a href="https://stackoverflow.com/questions/1088113/is-there-a-java-library-of-unix-functions">Posix JNI implementations</a>.</p>\n\n<ul>\n<li><a href="http://kenai.com/projects/jna-posix" rel="nofollow noreferrer">JNA-POSIX</a></li>\n<li><a href="http://www.bmsi.com/java/posix/" rel="nofollow noreferrer">POSIX for Java</a></li>\n</ul>\n\n<p>In particular, JNA-POSIX implements <a href="http://kenai.com/projects/jna-posix/sources/mercurial/content/src/org/jruby/ext/posix/FileStat.java?rev=59" rel="nofollow noreferrer">methods for getting file stats</a> with implementations for <a href="http://kenai.com/projects/jna-posix/sources/mercurial/content/src/org/jruby/ext/posix/WindowsFileStat.java?rev=59" rel="nofollow noreferrer">Windows</a>, BSD, Solaris, Linux and OSX.</p>\n\n<p>All in all it looks very promising, so I\'ll be trying it out on my own project very soon.</p>\n'}, {'answer_id': 3350512, 'author': 'LiuYan 刘研', 'author_id': 404192, 'author_profile': 'https://Stackoverflow.com/users/404192', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve wrote a small test class some days ago, wish it can help you:</p>\n\n<pre><code>// Get/Set windows file CreationTime/LastWriteTime/LastAccessTime\n// Test with jna-3.2.7\n// [http://maclife.net/wiki/index.php?title=Java_get_and_set_windows_system_file_creation_time_via_JNA_(Java_Native_Access)][1]\n\nimport java.io.*;\nimport java.nio.*;\nimport java.util.Date;\n\n// Java Native Access library: jna.dev.java.net\nimport com.sun.jna.*;\nimport com.sun.jna.ptr.*;\nimport com.sun.jna.win32.*;\nimport com.sun.jna.platform.win32.*;\n\npublic class WindowsFileTime\n{\n    public static final int GENERIC_READ = 0x80000000;\n    //public static final int GENERIC_WRITE = 0x40000000;   // defined in com.sun.jna.platform.win32.WinNT\n    public static final int GENERIC_EXECUTE = 0x20000000;\n    public static final int GENERIC_ALL = 0x10000000;\n\n    // defined in com.sun.jna.platform.win32.WinNT\n    //public static final int CREATE_NEW = 1;\n    //public static final int CREATE_ALWAYS = 2;\n    //public static final int OPEN_EXISTING = 3;\n    //public static final int OPEN_ALWAYS = 4;\n    //public static final int TRUNCATE_EXISTING = 5;\n\n    public interface MoreKernel32 extends Kernel32\n    {\n        static final MoreKernel32 instance = (MoreKernel32)Native.loadLibrary ("kernel32", MoreKernel32.class, W32APIOptions.DEFAULT_OPTIONS);\n        boolean GetFileTime (WinNT.HANDLE hFile, WinBase.FILETIME lpCreationTime, WinBase.FILETIME lpLastAccessTime, WinBase.FILETIME lpLastWriteTime);\n        boolean SetFileTime (WinNT.HANDLE hFile, final WinBase.FILETIME lpCreationTime, final WinBase.FILETIME lpLastAccessTime, final WinBase.FILETIME lpLastWriteTime);\n    }\n\n    static MoreKernel32 win32 = MoreKernel32.instance;\n    //static Kernel32 _win32 = (Kernel32)win32;\n\n    static WinBase.FILETIME _creationTime = new WinBase.FILETIME ();\n    static WinBase.FILETIME _lastWriteTime = new WinBase.FILETIME ();\n    static WinBase.FILETIME _lastAccessTime = new WinBase.FILETIME ();\n\n    static boolean GetFileTime (String sFileName, Date creationTime, Date lastWriteTime, Date lastAccessTime)\n    {\n        WinNT.HANDLE hFile = OpenFile (sFileName, GENERIC_READ);    // may be WinNT.GENERIC_READ in future jna version.\n        if (hFile == WinBase.INVALID_HANDLE_VALUE) return false;\n\n        boolean rc = win32.GetFileTime (hFile, _creationTime, _lastAccessTime, _lastWriteTime);\n        if (rc)\n        {\n            if (creationTime != null) creationTime.setTime (_creationTime.toLong());\n            if (lastAccessTime != null) lastAccessTime.setTime (_lastAccessTime.toLong());\n            if (lastWriteTime != null) lastWriteTime.setTime (_lastWriteTime.toLong());\n        }\n        else\n        {\n            int iLastError = win32.GetLastError();\n            System.out.print ("获取文件时间失败，错误码：" + iLastError + " " + GetWindowsSystemErrorMessage (iLastError));\n        }\n        win32.CloseHandle (hFile);\n        return rc;\n    }\n    static boolean SetFileTime (String sFileName, final Date creationTime, final Date lastWriteTime, final Date lastAccessTime)\n    {\n        WinNT.HANDLE hFile = OpenFile (sFileName, WinNT.GENERIC_WRITE);\n        if (hFile == WinBase.INVALID_HANDLE_VALUE) return false;\n\n        ConvertDateToFILETIME (creationTime, _creationTime);\n        ConvertDateToFILETIME (lastWriteTime, _lastWriteTime);\n        ConvertDateToFILETIME (lastAccessTime, _lastAccessTime);\n\n        //System.out.println ("creationTime: " + creationTime);\n        //System.out.println ("lastWriteTime: " + lastWriteTime);\n        //System.out.println ("lastAccessTime: " + lastAccessTime);\n\n        //System.out.println ("_creationTime: " + _creationTime);\n        //System.out.println ("_lastWriteTime: " + _lastWriteTime);\n        //System.out.println ("_lastAccessTime: " + _lastAccessTime);\n\n        boolean rc = win32.SetFileTime (hFile, creationTime==null?null:_creationTime, lastAccessTime==null?null:_lastAccessTime, lastWriteTime==null?null:_lastWriteTime);\n        if (! rc)\n        {\n            int iLastError = win32.GetLastError();\n            System.out.print ("设置文件时间失败，错误码：" + iLastError + " " + GetWindowsSystemErrorMessage (iLastError));\n        }\n        win32.CloseHandle (hFile);\n        return rc;\n    }\n    static void ConvertDateToFILETIME (Date date, WinBase.FILETIME ft)\n    {\n        if (ft != null)\n        {\n            long iFileTime = 0;\n            if (date != null)\n            {\n                iFileTime = WinBase.FILETIME.dateToFileTime (date);\n                ft.dwHighDateTime = (int)((iFileTime &gt;&gt; 32) &amp; 0xFFFFFFFFL);\n                ft.dwLowDateTime = (int)(iFileTime &amp; 0xFFFFFFFFL);\n            }\n            else\n            {\n                ft.dwHighDateTime = 0;\n                ft.dwLowDateTime = 0;\n            }\n        }\n    }\n\n    static WinNT.HANDLE OpenFile (String sFileName, int dwDesiredAccess)\n    {\n        WinNT.HANDLE hFile = win32.CreateFile (\n            sFileName,\n            dwDesiredAccess,\n            0,\n            null,\n            WinNT.OPEN_EXISTING,\n            0,\n            null\n            );\n        if (hFile == WinBase.INVALID_HANDLE_VALUE)\n        {\n            int iLastError = win32.GetLastError();\n            System.out.print (" 打开文件失败，错误码：" + iLastError + " " + GetWindowsSystemErrorMessage (iLastError));\n        }\n        return hFile;\n    }\n    static String GetWindowsSystemErrorMessage (int iError)\n    {\n        char[] buf = new char[255];\n        CharBuffer bb = CharBuffer.wrap (buf);\n        //bb.clear ();\n        //PointerByReference pMsgBuf = new PointerByReference ();\n        int iChar = win32.FormatMessage (\n                WinBase.FORMAT_MESSAGE_FROM_SYSTEM\n                    //| WinBase.FORMAT_MESSAGE_IGNORE_INSERTS\n                    //|WinBase.FORMAT_MESSAGE_ALLOCATE_BUFFER\n                    ,\n                null,\n                iError,\n                0x0804,\n                bb, buf.length,\n                //pMsgBuf, 0,\n                null\n            );\n        //for (int i=0; i&lt;iChar; i++)\n        //{\n        //  System.out.print (" ");\n        //  System.out.print (String.format("%02X", buf[i]&amp;0xFFFF));\n        //}\n        bb.limit (iChar);\n        //System.out.print (bb);\n        //System.out.print (pMsgBuf.getValue().getString(0));\n        //win32.LocalFree (pMsgBuf.getValue());\n        return bb.toString ();\n    }\n\n    public static void main (String[] args) throws Exception\n    {\n        if (args.length == 0)\n        {\n            System.out.println ("获取 Windows 的文件时间（创建时间、最后修改时间、最后访问时间）");\n            System.out.println ("用法：");\n            System.out.println ("   java -cp .;..;jna.jar;platform.jar WindowsFileTime [文件名1] [文件名2]...");\n            return;\n        }\n\n        boolean rc;\n        java.sql.Timestamp ct = new java.sql.Timestamp(0);\n        java.sql.Timestamp wt = new java.sql.Timestamp(0);\n        java.sql.Timestamp at = new java.sql.Timestamp(0);\n\n        for (String sFileName : args)\n        {\n            System.out.println ("文件 " + sFileName);\n\n            rc = GetFileTime (sFileName, ct, wt, at);\n            if (rc)\n            {\n                System.out.println ("   创建时间：" + ct);\n                System.out.println ("   修改时间：" + wt);\n                System.out.println ("   访问时间：" + at);\n            }\n            else\n            {\n                //System.out.println ("GetFileTime 失败");\n            }\n\n\n            //wt.setTime (System.currentTimeMillis());\n            wt = java.sql.Timestamp.valueOf("2010-07-23 00:00:00");\n            rc = SetFileTime (sFileName, null, wt, null);\n            if (rc)\n            {\n                System.out.println ("SetFileTime (最后修改时间) 成功");\n            }\n            else\n            {\n                //System.out.println ("SetFileTime 失败");\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 6185263, 'author': 'Kamal', 'author_id': 777363, 'author_profile': 'https://Stackoverflow.com/users/777363', 'pm_score': 2, 'selected': False, 'text': '<pre><code>import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\n\npublic class CreateDateInJava {\n    public static void main(String args[]) {\n        try {\n\n            // get runtime environment and execute child process\n            Runtime systemShell = Runtime.getRuntime();\n            BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));\n            System.out.println("Enter filename: ");\n            String fname = (String) br1.readLine();\n            Process output = systemShell.exec("cmd /c dir \\"" + fname + "\\" /tc");\n\n            System.out.println(output);\n            // open reader to get output from process\n            BufferedReader br = new BufferedReader(new InputStreamReader(output.getInputStream()));\n\n            String out = "";\n            String line = null;\n\n            int step = 1;\n            while ((line = br.readLine()) != null) {\n                if (step == 6) {\n                    out = line;\n                }\n                step++;\n            }\n\n            // display process output\n            try {\n                out = out.replaceAll(" ", "");\n                System.out.println("CreationDate: " + out.substring(0, 10));\n                System.out.println("CreationTime: " + out.substring(10, 16) + "m");\n            } catch (StringIndexOutOfBoundsException se) {\n                System.out.println("File not found");\n            }\n        } catch (IOException ioe) {\n            System.err.println(ioe);\n        } catch (Throwable t) {\n            t.printStackTrace();\n        }\n    }\n}\n\n/**\nD:\\Foldername\\Filename.Extension\n\nEx:\nEnter Filename :\nD:\\Kamal\\Test.txt\nCreationDate: 02/14/2011\nCreationTime: 12:59Pm\n\n*/\n</code></pre>\n'}, {'answer_id': 14287216, 'author': 'Peter', 'author_id': 777443, 'author_profile': 'https://Stackoverflow.com/users/777443', 'pm_score': 2, 'selected': False, 'text': '<p>The <a href="http://www.javaxt.com" rel="nofollow">javaxt-core</a> library includes a File class that can be used to retrieve file attributes, including the creation time. Example:</p>\n\n<pre><code>javaxt.io.File file = new javaxt.io.File("/temp/file.txt");\nSystem.out.println("Created: " + file.getCreationTime());\nSystem.out.println("Accessed: " + file.getLastAccessTime());\nSystem.out.println("Modified: " + file.getLastModifiedTime());\n</code></pre>\n\n<p>Works with Java 1.5 and up.</p>\n'}, {'answer_id': 16969301, 'author': 'ajon', 'author_id': 1068058, 'author_profile': 'https://Stackoverflow.com/users/1068058', 'pm_score': 4, 'selected': False, 'text': '<p>With the release of Java 7 there is a built-in way to do this:</p>\n\n<pre><code>Path path = Paths.get("path/to/file");\nBasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);\nFileTime creationTime = attributes.creationTime();\n</code></pre>\n\n<p>It is important to note that not all operating systems provide this information.  I believe in those instances this returns the mtime which is the last modified time.</p>\n\n<p>Windows does provide creation time.</p>\n'}, {'answer_id': 32771938, 'author': 'Jorgesys', 'author_id': 250260, 'author_profile': 'https://Stackoverflow.com/users/250260', 'pm_score': 0, 'selected': False, 'text': '<p>This is a basic example in <code>Java</code>, using <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/BasicFileAttributes.html" rel="nofollow"><strong><code>BasicFileAttributes</code></strong></a> class:</p>\n\n<pre><code>   Path path = Paths.get("C:\\\\Users\\\\jorgesys\\\\workspaceJava\\\\myfile.txt");\n    BasicFileAttributes attr;\n    try {\n      attr = Files.readAttributes(path, BasicFileAttributes.class);\n      System.out.println("File creation time: " + attr.creationTime());\n    } catch (IOException e) {\n      System.out.println("oops un error! " + e.getMessage());\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/32586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471/']