`

[java]nio.2 java.nio.file.*使用初探

 
阅读更多

内容参考了:

http://zjumty.iteye.com/blog/1896350

当做一个练习然后加上自己的想法吧:

 

集合在了java.nio.file下的一些类的使用

 

 

Path:

使用Paths这个工具类可以生成Path

代表地址 这个类主要处理一些地址的生成操作 比如在已有Path下得到子文件的地址 得到文件的相对地址等等,使用起来很简单,这边列几个方法(更多的可以参考链接里的地址):

package test.nio;

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathTest {

	public static void main(String[] args) {
		Path file=Paths.get("G:", "新建文件夹");
		System.out.format("file:%s \n", file);
		
		//是否以所给的字符或者Path结尾(这边不写 新建文件夹 的会是false)
		System.out.println(file.endsWith("新建文件夹"));

		//在当前path下增加 输出:G:\新建文件夹\abc.txt 
		Path file2=file.resolve("abc.txt");
		System.out.format("file2:%s \n",file2);
		
		//在当前path所在的目录中增加 输出:G:\新建文件夹\1 
		Path file3=file2.resolveSibling("1");
		System.out.format("file3:%s \n",file3);
		
		// 相对路径 输出:..\1 file3相对于file2的路径
		Path file4=file2.relativize(file3);
		System.out.format("file4:%s \n",file4);
		
		// 获取名字数量 输出都为:2
		System.out.format("file3 namecount:%d \n",file3.getNameCount());
		System.out.format("file4 namecount:%d \n",file4.getNameCount());
		
		// 输出新建文件夹
		System.out.format("file3 getName(0):%s \n",file3.getName(0));
		
		// 返回G:\  G:\新建文件夹\1 可见nameCount只记录 新建文件夹 和 1 G:\需要通过getRoot获取
		System.out.format("file3 getRoot():%s \n",file3.getRoot());
		// 相对路径没有root 返回null 并且 ..\1  他的namecount记录的就是 ..和1
		System.out.format("file4 getRoot():%s \n",file4.getRoot());
		
		
	}

}

 

 

 

File Attriubute:

通过工具类Files获取

属性相关的类是 java.nio.file.attribute

 


BasicFileAttribute还有个BasicFileAttributeView

而这个View类里面只有三个方法:


 其中一个还是返回那个BasicFileAttributes的....
似乎这个View类唯一的功能就是改下修改时间了....而其他View类也提供一些修改的操作

(这里有些讨论:http://stackoverflow.com/questions/16374278/basicfileattributes-vs-basicfileattributeview-in-java)

可以理解成BasicFileAttribute就是存放相关数据 而对应的view类不仅可以取出数据还可以对数据进行修改

package test.nio;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;

public class FileAttribute {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		Path file=Paths.get("G:", "新建文件夹","abc.txt");
        BasicFileAttributeView bav=Files.getFileAttributeView(file, BasicFileAttributeView.class);
        
        BasicFileAttributes ba=bav.readAttributes();
        //或者:
        //BasicFileAttributes ba=Files.readAttributes(file, BasicFileAttributes.class);
        System.out.format("File size: %s \n" , ba.size());  
        System.out.format("File creation time: %s \n" , ba.creationTime());  
        System.out.format("File was last accessed at: %s \n" , ba.lastAccessTime());  
        System.out.format("File was last modified at: %s \n" , ba.lastModifiedTime());  
        System.out.format("Is directory? %s \n" , ba.isDirectory());  
        System.out.format("Is regular file? %s \n" , ba.isRegularFile());  
        System.out.format("Is symbolic link? %s \n" , ba.isSymbolicLink());  
        System.out.format("Is other? %s \n" , ba.isOther());  
	}

}
结果 
File size: 0
File creation time: 2013-07-24T08:36:50.93237Z
File was last accessed at: 2013-07-24T08:36:50.93237Z
File was last modified at: 2013-07-24T08:36:50.93237Z
Is directory? false
Is regular file? true
Is symbolic link? false
Is other? false

 

 

 

 

 

读取整个目录的文件:

用DirectoryStream这个类就可以完成

诸如:

DirectoryStream<Path> ds=Files.newDirectoryStream(file, "*")

 的形式 其中第一个参数是Path ,第二个参数是String(还有其他的重载方法)

第二个参数可以是通配符 有很多种的书写方式(详细的可以看FileSystem的getPath() http://openjdk.java.net/projects/nio/javadoc/java/nio/file/FileSystem.html#getPathMatcher(java.lang.String))

以上文档中有一个在win7下C:\\也可以写成C:/ 试验了下没问题

package test.nio;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DirectoryStreamTest {

	public static void main(String[] args) throws IOException {
		Path file=Paths.get("G:/新建文件夹");
        try(DirectoryStream<Path> ds=Files.newDirectoryStream(file, "*")){
        	for(Path p:ds){
        		System.out.format("file name :%s \n",p);
        	}
        }
	}

}

 

...先写到这..等等再写

 

 

--接着写点:

FileVisitor使用:

代码如下 使用了FileVistor并覆写了所有的方法

也可以使用SimpleFileVistor来选择需要的方法:

package test.nio;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;

public class FileVistorTest {

	public static void main(String[] args) throws IOException {
		Path file=Paths.get("G:/","新建文件夹");
		Files.walkFileTree(file, new FileVisitor<Path>(){
		    @Override
		    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
		        throws IOException
		    {
		        System.out.format("visit file %s \n",file);
		        return FileVisitResult.CONTINUE;
		    }

			@Override
			public FileVisitResult preVisitDirectory(Path dir,
					BasicFileAttributes attrs) throws IOException {
				 System.out.format("preVisitDirectory %s \n",dir);
				return FileVisitResult.CONTINUE;
			}

			@Override
			public FileVisitResult visitFileFailed(Path file, IOException exc)
					throws IOException {
				 System.out.format("visitFileFailed %s \n",file);
				return FileVisitResult.CONTINUE;
			}

			@Override
			public FileVisitResult postVisitDirectory(Path dir, IOException exc)
					throws IOException {
				System.out.format("postVisitDirectory %s \n",dir);
				return FileVisitResult.CONTINUE;
			}
		});

	}

}
输出 :
preVisitDirectory G:\新建文件夹
preVisitDirectory G:\新建文件夹\1
postVisitDirectory G:\新建文件夹\1
visit file G:\新建文件夹\abc.txt
visit file G:\新建文件夹\autorun.inf
preVisitDirectory G:\新建文件夹\cc
visit file G:\新建文件夹\cc\c01.txt
visit file G:\新建文件夹\cc\c02.txt
postVisitDirectory G:\新建文件夹\cc
visit file G:\新建文件夹\h.ico
postVisitDirectory G:\新建文件夹

 根据方法名和输出很容易就可以知道是什么意思

需要注意的是:FileVisitResult 他是一个枚举类型 每个枚举值意思如下:

public enum FileVisitResult {
    /**
     * Continue. When returned from a {@link FileVisitor#preVisitDirectory
     * preVisitDirectory} method then the entries in the directory should also
     * be visited.
     * 在preVisitDirectory方法返回的话 目录下的文件(或目录)也会被被访问
     */
    CONTINUE,
    /**
     * Terminate. 结束
     */
    TERMINATE,
    /**
     * Continue without visiting the entries in this directory. This result
     * is only meaningful when returned from the {@link
     * FileVisitor#preVisitDirectory preVisitDirectory} method; otherwise
     * this result type is the same as returning {@link #CONTINUE}.
     * 只在preVistiDirectory这个方法中返回有意义 跳过目录下的文件
     */
    SKIP_SUBTREE,
    /**
     * Continue without visiting the <em>siblings</em> of this file or directory.
     * If returned from the {@link FileVisitor#preVisitDirectory
     * preVisitDirectory} method then the entries in the directory are also
     * skipped and the {@link FileVisitor#postVisitDirectory postVisitDirectory}
     * method is not invoked.
     * 跳过同一层目录的 如果在preVisitDirectory里使用 那么    postVisitDiretory这个方法就不会被触发
     */
    SKIP_SIBLINGS;
}

 

Watch Service API 

这个IBM-developer有个很好的示例 这边就不在多说了

http://www.ibm.com/developerworks/cn/java/j-lo-nio2fs/

  • 大小: 13.4 KB
  • 大小: 17.6 KB
分享到:
评论

相关推荐

    java NIO.zip

    java NIO.zip

    java nio.pdf

    java nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava nio.pdfjava ...

    Java NIO.pdf

    Java NIO.pdf Java NIO.pdf Java NIO.pdf Java NIO.pdf Java NIO.pdf Java NIO.pdf

    Java IO, NIO and NIO.2(Apress,2015)

    Java I/O, NIO, and NIO.2 is a power-packed book that accelerates your mastery of Java's various I/O APIs. In this book, you'll learn about classic I/O APIs (File, RandomAccessFile, the stream classes ...

    Java IO, NIO and NIO.2 原版pdf by Friesen

    Chapters 12 through 14 cover NIO.2’s improved file system interface, asynchronous I/O, and the completion of socket channel functionality. Each chapter ends with assorted exercises that are designed...

    JavaNIO.pdf

    JavaNIO.pdf

    java NIO详细教程

    java NIO详细教程,包括使用背景,实现原理,代码实现

    java.io:clojure.java.io 的 JK7 java.nio.file.Path 兼容性

    java.io clojure.java.io 的 JK7 java.nio.file.Path 兼容性依赖信息该库托管在 Releases 上。 依赖: [me.moocar/java.io " 0.1.0 " ]用法是 JDK7 中引入的文件路径的抽象。 这个库提供了和 Paths 之间的兼容性。 ...

    Java NIO 中英文版 + Pro Java 7 NIO.2

    Java NIO,Ron Hitchens 著,中文版 裴小星 译,Pro Java 7 NIO.2,Anghel Leonard 著,pdf文字版带书签,无安全限制

    优雅的操作文件:java.nio.file 库介绍.pdf

    但 Java 在后期版本中引入了 java.nio.file 库来提高 Java 对文件操作的能力。还增加的流的功能,似乎使得文件变成更好用了。所以本章,我们就来主要介绍 java.nio.file 中常用的类和模块,大致如下: Path 路径:...

    java nio.doc

    java.nio.charset 包中定义了字符集 API,java.nio.channels 包中定义了信道和选择器 API。每个子包都具有自己的服务提供程序接口 (SPI) 子包,SPI 子包的内容可用于扩展平台的默认实现或构造替代实现。

    Java NIO.docx

    Java NIO.docx

    JDK1.7 之java.nio.file.Files 读取文件仅需一行代码实现

    下面小编就为大家分享一篇JDK1.7 之java.nio.file.Files 读取文件仅需一行代码实现,具有很好的参考价值,希望对大家有所帮助

    java org.apache.http.nio jar包

    找了好久,终于找到了,java刷新同步获取网络资源

    java_nio.doc

    用java.nio.*进行网络编程

    Java IO, NIO and NIO.2

    这是一本介绍java io以及nio相关知识的书,书中对知识的讲解通俗易懂,是学习java nio以及复习java io相关知识的必备书籍。注意:本书为英文版!!!

    nio.file:java.nio.file 的 Clojure 包装器

    nio.file java.nio.file 的 Clojure 包装器为什么要这样做? 看看 。 工作正在进行中! 在我们达到 1.0.0 之前,预计会有错误和缺失的功能。支持的 Clojure 和 Java 版本nio.file针对 Clojure nio.file和 Java 1.7+...

Global site tag (gtag.js) - Google Analytics