2008-08-28 18 views
23

有沒有一種簡單的方法來發現文件的Java創建時間? File類只有一個獲取「上次修改」時間的方法。根據我在Google上發現的一些資源,File類沒有提供getCreationTime()方法,因爲並非所有文件系統都支持創建時間的想法。如何用Java發現文件的創建時間?

唯一的工作解決方案是我發現了輸入命令行並執行「dir」命令的involes,它看起來像輸出文件的創建時間。我猜這是有效的,我只需要支持Windows,但似乎很容易出錯。

是否有任何第三方庫提供我需要的信息?

更新:最後,我認爲這不值得我購買第三方庫,但他們的API確實很不錯,所以對於有這個問題的其他人來說,這可能是一個不錯的選擇。

+0

我檢查[Apache的百科全書VFS(http://commons.apache.org/vfs/),其中虛擬文件系統可以導出一組豐富的功能。但不幸的是,沒有定義CREATION_TIME功能。 – 2011-01-10 08:31:30

+0

AFAIK,NIO-2解決了這個問題,但尚未發佈(應該是第7版)。請參閱http://java.sun.com/developer/technicalArticles/javase/nio/和http://today.java.net/article/2009/10/14/sweeping-file-system-nio-2 – 2011-03-07 13:04:06

回答

1

我喜歡jGuru的答案,該答案列出了使用JNI獲得答案的選項。這可能比脫殼更快,您可能會遇到其他情況,例如需要專門針對Windows執行的情況。另外,如果你需要移植到不同的平臺上,那麼你也可以移植你的庫,並且只要返回-1就可以在* ix上得到這個問題的答案。

7

我前幾天寫了一個小測試類,希望它可以幫助你:

// Get/Set windows file CreationTime/LastWriteTime/LastAccessTime 
// Test with jna-3.2.7 
// [http://maclife.net/wiki/index.php?title=Java_get_and_set_windows_system_file_creation_time_via_JNA_(Java_Native_Access)][1] 

import java.io.*; 
import java.nio.*; 
import java.util.Date; 

// Java Native Access library: jna.dev.java.net 
import com.sun.jna.*; 
import com.sun.jna.ptr.*; 
import com.sun.jna.win32.*; 
import com.sun.jna.platform.win32.*; 

public class WindowsFileTime 
{ 
    public static final int GENERIC_READ = 0x80000000; 
    //public static final int GENERIC_WRITE = 0x40000000; // defined in com.sun.jna.platform.win32.WinNT 
    public static final int GENERIC_EXECUTE = 0x20000000; 
    public static final int GENERIC_ALL = 0x10000000; 

    // defined in com.sun.jna.platform.win32.WinNT 
    //public static final int CREATE_NEW = 1; 
    //public static final int CREATE_ALWAYS = 2; 
    //public static final int OPEN_EXISTING = 3; 
    //public static final int OPEN_ALWAYS = 4; 
    //public static final int TRUNCATE_EXISTING = 5; 

    public interface MoreKernel32 extends Kernel32 
    { 
     static final MoreKernel32 instance = (MoreKernel32)Native.loadLibrary ("kernel32", MoreKernel32.class, W32APIOptions.DEFAULT_OPTIONS); 
     boolean GetFileTime (WinNT.HANDLE hFile, WinBase.FILETIME lpCreationTime, WinBase.FILETIME lpLastAccessTime, WinBase.FILETIME lpLastWriteTime); 
     boolean SetFileTime (WinNT.HANDLE hFile, final WinBase.FILETIME lpCreationTime, final WinBase.FILETIME lpLastAccessTime, final WinBase.FILETIME lpLastWriteTime); 
    } 

    static MoreKernel32 win32 = MoreKernel32.instance; 
    //static Kernel32 _win32 = (Kernel32)win32; 

    static WinBase.FILETIME _creationTime = new WinBase.FILETIME(); 
    static WinBase.FILETIME _lastWriteTime = new WinBase.FILETIME(); 
    static WinBase.FILETIME _lastAccessTime = new WinBase.FILETIME(); 

    static boolean GetFileTime (String sFileName, Date creationTime, Date lastWriteTime, Date lastAccessTime) 
    { 
     WinNT.HANDLE hFile = OpenFile (sFileName, GENERIC_READ); // may be WinNT.GENERIC_READ in future jna version. 
     if (hFile == WinBase.INVALID_HANDLE_VALUE) return false; 

     boolean rc = win32.GetFileTime (hFile, _creationTime, _lastAccessTime, _lastWriteTime); 
     if (rc) 
     { 
      if (creationTime != null) creationTime.setTime (_creationTime.toLong()); 
      if (lastAccessTime != null) lastAccessTime.setTime (_lastAccessTime.toLong()); 
      if (lastWriteTime != null) lastWriteTime.setTime (_lastWriteTime.toLong()); 
     } 
     else 
     { 
      int iLastError = win32.GetLastError(); 
      System.out.print ("獲取文件時間失敗,錯誤碼:" + iLastError + " " + GetWindowsSystemErrorMessage (iLastError)); 
     } 
     win32.CloseHandle (hFile); 
     return rc; 
    } 
    static boolean SetFileTime (String sFileName, final Date creationTime, final Date lastWriteTime, final Date lastAccessTime) 
    { 
     WinNT.HANDLE hFile = OpenFile (sFileName, WinNT.GENERIC_WRITE); 
     if (hFile == WinBase.INVALID_HANDLE_VALUE) return false; 

     ConvertDateToFILETIME (creationTime, _creationTime); 
     ConvertDateToFILETIME (lastWriteTime, _lastWriteTime); 
     ConvertDateToFILETIME (lastAccessTime, _lastAccessTime); 

     //System.out.println ("creationTime: " + creationTime); 
     //System.out.println ("lastWriteTime: " + lastWriteTime); 
     //System.out.println ("lastAccessTime: " + lastAccessTime); 

     //System.out.println ("_creationTime: " + _creationTime); 
     //System.out.println ("_lastWriteTime: " + _lastWriteTime); 
     //System.out.println ("_lastAccessTime: " + _lastAccessTime); 

     boolean rc = win32.SetFileTime (hFile, creationTime==null?null:_creationTime, lastAccessTime==null?null:_lastAccessTime, lastWriteTime==null?null:_lastWriteTime); 
     if (! rc) 
     { 
      int iLastError = win32.GetLastError(); 
      System.out.print ("設置文件時間失敗,錯誤碼:" + iLastError + " " + GetWindowsSystemErrorMessage (iLastError)); 
     } 
     win32.CloseHandle (hFile); 
     return rc; 
    } 
    static void ConvertDateToFILETIME (Date date, WinBase.FILETIME ft) 
    { 
     if (ft != null) 
     { 
      long iFileTime = 0; 
      if (date != null) 
      { 
       iFileTime = WinBase.FILETIME.dateToFileTime (date); 
       ft.dwHighDateTime = (int)((iFileTime >> 32) & 0xFFFFFFFFL); 
       ft.dwLowDateTime = (int)(iFileTime & 0xFFFFFFFFL); 
      } 
      else 
      { 
       ft.dwHighDateTime = 0; 
       ft.dwLowDateTime = 0; 
      } 
     } 
    } 

    static WinNT.HANDLE OpenFile (String sFileName, int dwDesiredAccess) 
    { 
     WinNT.HANDLE hFile = win32.CreateFile (
      sFileName, 
      dwDesiredAccess, 
      0, 
      null, 
      WinNT.OPEN_EXISTING, 
      0, 
      null 
      ); 
     if (hFile == WinBase.INVALID_HANDLE_VALUE) 
     { 
      int iLastError = win32.GetLastError(); 
      System.out.print (" 打開文件失敗,錯誤碼:" + iLastError + " " + GetWindowsSystemErrorMessage (iLastError)); 
     } 
     return hFile; 
    } 
    static String GetWindowsSystemErrorMessage (int iError) 
    { 
     char[] buf = new char[255]; 
     CharBuffer bb = CharBuffer.wrap (buf); 
     //bb.clear(); 
     //PointerByReference pMsgBuf = new PointerByReference(); 
     int iChar = win32.FormatMessage (
       WinBase.FORMAT_MESSAGE_FROM_SYSTEM 
        //| WinBase.FORMAT_MESSAGE_IGNORE_INSERTS 
        //|WinBase.FORMAT_MESSAGE_ALLOCATE_BUFFER 
        , 
       null, 
       iError, 
       0x0804, 
       bb, buf.length, 
       //pMsgBuf, 0, 
       null 
      ); 
     //for (int i=0; i<iChar; i++) 
     //{ 
     // System.out.print (" "); 
     // System.out.print (String.format("%02X", buf[i]&0xFFFF)); 
     //} 
     bb.limit (iChar); 
     //System.out.print (bb); 
     //System.out.print (pMsgBuf.getValue().getString(0)); 
     //win32.LocalFree (pMsgBuf.getValue()); 
     return bb.toString(); 
    } 

    public static void main (String[] args) throws Exception 
    { 
     if (args.length == 0) 
     { 
      System.out.println ("獲取 Windows 的文件時間(創建時間、最後修改時間、最後訪問時間)"); 
      System.out.println ("用法:"); 
      System.out.println (" java -cp .;..;jna.jar;platform.jar WindowsFileTime [文件名1] [文件名2]..."); 
      return; 
     } 

     boolean rc; 
     java.sql.Timestamp ct = new java.sql.Timestamp(0); 
     java.sql.Timestamp wt = new java.sql.Timestamp(0); 
     java.sql.Timestamp at = new java.sql.Timestamp(0); 

     for (String sFileName : args) 
     { 
      System.out.println ("文件 " + sFileName); 

      rc = GetFileTime (sFileName, ct, wt, at); 
      if (rc) 
      { 
       System.out.println (" 創建時間:" + ct); 
       System.out.println (" 修改時間:" + wt); 
       System.out.println (" 訪問時間:" + at); 
      } 
      else 
      { 
       //System.out.println ("GetFileTime 失敗"); 
      } 


      //wt.setTime (System.currentTimeMillis()); 
      wt = java.sql.Timestamp.valueOf("2010-07-23 00:00:00"); 
      rc = SetFileTime (sFileName, null, wt, null); 
      if (rc) 
      { 
       System.out.println ("SetFileTime (最後修改時間) 成功"); 
      } 
      else 
      { 
       //System.out.println ("SetFileTime 失敗"); 
      } 
     } 
    } 
} 
2
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 


public class CreateDateInJava { 
    public static void main(String args[]) { 
     try { 

      // get runtime environment and execute child process 
      Runtime systemShell = Runtime.getRuntime(); 
      BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in)); 
      System.out.println("Enter filename: "); 
      String fname = (String) br1.readLine(); 
      Process output = systemShell.exec("cmd /c dir \"" + fname + "\" /tc"); 

      System.out.println(output); 
      // open reader to get output from process 
      BufferedReader br = new BufferedReader(new InputStreamReader(output.getInputStream())); 

      String out = ""; 
      String line = null; 

      int step = 1; 
      while ((line = br.readLine()) != null) { 
       if (step == 6) { 
        out = line; 
       } 
       step++; 
      } 

      // display process output 
      try { 
       out = out.replaceAll(" ", ""); 
       System.out.println("CreationDate: " + out.substring(0, 10)); 
       System.out.println("CreationTime: " + out.substring(10, 16) + "m"); 
      } catch (StringIndexOutOfBoundsException se) { 
       System.out.println("File not found"); 
      } 
     } catch (IOException ioe) { 
      System.err.println(ioe); 
     } catch (Throwable t) { 
      t.printStackTrace(); 
     } 
    } 
} 

/** 
D:\Foldername\Filename.Extension 

Ex: 
Enter Filename : 
D:\Kamal\Test.txt 
CreationDate: 02/14/2011 
CreationTime: 12:59Pm 

*/ 
2

javaxt-core庫包括可用於檢索文件屬性的文件類,包括創作時間。示例:

javaxt.io.File file = new javaxt.io.File("/temp/file.txt"); 
System.out.println("Created: " + file.getCreationTime()); 
System.out.println("Accessed: " + file.getLastAccessTime()); 
System.out.println("Modified: " + file.getLastModifiedTime()); 

適用於Java 1.5及更高版本。

21

在Java 7的發佈有一個內置的方式做到這一點:

Path path = Paths.get("path/to/file"); 
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); 
FileTime creationTime = attributes.creationTime(); 

重要的是要注意,並非所有的操作系​​統都提供這個信息是非常重要的。我相信在這些情況下,這將返回最後修改時間的mtime。

Windows確實提供了創建時間。

0

這是Java一個基本的例子,使用BasicFileAttributes類:

Path path = Paths.get("C:\\Users\\jorgesys\\workspaceJava\\myfile.txt"); 
    BasicFileAttributes attr; 
    try { 
     attr = Files.readAttributes(path, BasicFileAttributes.class); 
     System.out.println("File creation time: " + attr.creationTime()); 
    } catch (IOException e) { 
     System.out.println("oops un error! " + e.getMessage()); 
    }