设置和获取文件元数据--basic

  • 设置
    /**
     * 设置文件的最后修改时间/创建时间/最后访问时间
    * @param path
     */
    private static void set(Path path) {
    	long time = System.currentTimeMillis();
    		
    	FileTime fileTime = FileTime.fromMillis(time);
    		
    	try {
    		Files.setAttribute(path, "basic:lastModifiedTime", fileTime, LinkOption.NOFOLLOW_LINKS);
    		Files.setAttribute(path, "basic:creationTime", fileTime, LinkOption.NOFOLLOW_LINKS);
    		Files.setAttribute(path, "basic:lastAccessTime", fileTime, LinkOption.NOFOLLOW_LINKS);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    		
    }

  • 获取文件最后修改时间/创建时间/最后访问时间
    /**
    * 获取文件的最后修改时间/创建时间/访问时间
    * @param path
    */
    private static void get(Path path) {
    	try {
    		FileTime lastModifiedTime = (FileTime) Files.getAttribute(path, "basic:lastModifiedTime", LinkOption.NOFOLLOW_LINKS);
    		FileTime creationTime = (FileTime) Files.getAttribute(path, "basic:creationTime", LinkOption.NOFOLLOW_LINKS);
    		FileTime lastAccessTime = (FileTime) Files.getAttribute(path, "basic:lastAccessTime", LinkOption.NOFOLLOW_LINKS);
    		
    		System.out.println("New last modified time: " + lastModifiedTime);
    		System.out.println("New creation time: " + creationTime);
    		System.out.println("New last access time: " + lastAccessTime);
    	} catch (IOException e) {
    			
    		e.printStackTrace();
    	}
    }

  • 获取文件最后修改时间
    /**
    * 获取文件最后修改时间
    * @param path
    */
    private static void get_lastModifiedTime(Path path) {
    	try {
    		FileTime lastModifiedTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
    			
    		System.out.println("New last modified time: " + lastModifiedTime);
           } catch (IOException e) {
    	   e.printStackTrace();
           }
    }

  • 测试
    public static void main(String[] args) {
    	Path path = Paths.get("F:/cn/icer/ws/client/Business.java");
    		
    	//设置
    	set(path);
    		
    	//获取
    	get(path);
    		
    	//获取最后修改时间
    	get_lastModifiedTime(path);
    }


你可能感兴趣的:(Pro,Java,7,NIO,2)