开发者社区> 问答> 正文

Java 7 的文件操作:创建目录和读取目录内容:报错

我们来看看 Java 7 怎样对目录进行操作。首先我们来看看怎样列出一个文件系统中所有的更目录,就象我们在 Windows中 看到有多少硬盘分区(包括光盘等)。要得到这些信息,可以调用

FileSystem.getRootDirectories 方法。该方法返回一个 Iterable对象,我们可以遍历该对象得到所有 的根目录。该对象中的 每个元素都是一个 Path对象。具体的代码例子如下:

  1. import java.nio.file.FileSystems;  
  2.   
  3. import java.nio.file.Path;  
  4.   
  5.   
  6. public class RootDirectoryReader {  
  7.   
  8.         public static void main(String[] args){  
  9.   
  10.             Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();  
  11.   
  12.             for (Path name: dirs) {  
  13.   
  14.                 System.err.println(name);  
  15.   
  16.             }  
  17.   
  18.   
  19.         }  
  20.   
  21. }  
import java.nio.file.FileSystems;

import java.nio.file.Path;


public class RootDirectoryReader {

        public static void main(String[] args){

            Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();

            for (Path name: dirs) {

                System.err.println(name);

            }


        }

}
 

在 我的机器上运行该代码的输出如下:
C:\
D:\
E:\
F:\
G:\
在我的机器上, C盘是本地硬盘, D盘是光驱,其他 3个是移动硬盘的分区。

我们可以调用 Path类的 createDirectory方法来创建文件。如 果调用该方法是不传递任何参数,那么生成 的新的目录就拥有默认的属性。下面的代码就是创建一个拥有默认属性的新目录:

  1. Path dir = Paths.get("C:\\temp");  
  2.   
  3. try {  
  4.   
  5.     path.createDirectory();  
  6.   
  7. catch (IOException x) {  
  8.   
  9.     System.err.println(x);  
  10.   
  11. }  
    Path dir = Paths.get("C:\\temp");

    try {

        path.createDirectory();

    } catch (IOException x) {

        System.err.println(x);

    }
 

下面的代码是在 POSIX文件系统上创建一个拥有指定的属性的目 录:

  1. Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");  
  2.   
  3. FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);  
  4.   
  5. try {  
  6.   
  7.      file.createDirectory(attr);  
  8.   
  9. catch (IOException x) {  
  10.   
  11.      System.err.println(x);  
  12.   
  13. }  
    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");

    FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);

    try {

         file.createDirectory(attr);

    } catch (IOException x) {

         System.err.println(x);

    }

要 想创建一个多层的目录,如 c:\temp\first\abc这样的目录,我 们可以使用 Files类的 createDirectories方法。这个方法 接受 Path类作为第一个参数,第二个参数是可选的参数 FileAttribute。下面的代码创建具有缺 省属性的多层目录:

  1. try {  
  2.   
  3.      Files.createDirectories(Paths.get("c:\\temp\\first\\abc"));  
  4.   
  5. catch (IOException x) {  
  6.   
  7.      System.err.println(x);  
  8.   
  9. }  
    try {

         Files.createDirectories(Paths.get("c:\\temp\\first\\abc"));

    } catch (IOException x) {

         System.err.println(x);

    }


 

从 最上层开始,如果目录不存在,这创建新的目录。例如如果上面的目录层次中, c:\temp已经存在,则不再创建; c:\temp\first不存在,则直 接在 c:\temp下创建 first目录,然后在 first目录下创建 abc目录。
调用该方法的时候要注意该方法并不是原子操 作,也就是说目录层次可能有一部分成功,一部分失败。如上面的例子中,可能 first目录创建成功了,但是 abc目录创建失败了。

要想列出目录中所有的内容,可以调 用 newDirectoryStream()方法。该 方法返回一个实现了 DirectoryStream接口的对象。实 现了 DirectoryStream的对象同时也实现了 Iterable接口,因此我们可以遍历该对象。遍 历时得到的元素都是 Path对象。同时要注意的 是返回的 DirectoryStream也是一个流对象,别 忘记使用完之后关闭该对象。
下面是示例代码:

  1. Path dir = Paths.get("c:\\");     
  2.   
  3. DirectoryStream<Path> stream = null;  
  4.   
  5.     try {  
  6.   
  7.         stream = dir.newDirectoryStream();  
  8.   
  9.         for (Path file: stream) {  
  10.   
  11.             System.out.println(file.getName());  
  12.   
  13.         }  
  14.   
  15.     } catch (IOException x) {  
  16.   
  17.         //IOException can never be thrown by the iteration.  
  18.   
  19.         //In this snippet, it can only be thrown by newDirectoryStream.  
  20.   
  21.         System.err.println(x);  
  22.   
  23.     } finally {  
  24.   
  25.         if (stream != null) stream.close();  
  26.   
  27.     }  
Path dir = Paths.get("c:\\");   

DirectoryStream<Path> stream = null;

    try {

        stream = dir.newDirectoryStream();

        for (Path file: stream) {

            System.out.println(file.getName());

        }

    } catch (IOException x) {

        //IOException can never be thrown by the iteration.

        //In this snippet, it can only be thrown by newDirectoryStream.

        System.err.println(x);

    } finally {

        if (stream != null) stream.close();

    }


如果我们查找名字符合某些模式的文件或者只目录,我们可以调用 newDirectoryStream(String)方法。这个方法会调用一个内置的过滤 器来过滤返回的结果。关于模式的使用我们在前面的文章里已经讲过了。下面是具体的例子:

  1. Path dir = ...;  
  2.   
  3. DirectoryStream<Path> stream = null;  
  4.   
  5. try {  
  6.   
  7.     stream = dir.newDirectoryStream("*.{java,class,jar}");  
  8.   
  9.     for (Path entry: stream) {  
  10.   
  11.         System.out.println(entry.getName());  
  12.   
  13.     }  
  14.   
  15. catch (IOException x) {  
  16.   
  17.     //IOException can never be thrown by the iteration.  
  18.   
  19.     //In this snippet, it can only be thrown by newDirectoryStream.  
  20.   
  21.     System.err.println(x);  
  22.   
  23. finally {  
  24.   
  25.     if (stream != null) stream.close()  
  26.   
  27. }  
    Path dir = ...;

    DirectoryStream<Path> stream = null;

    try {

        stream = dir.newDirectoryStream("*.{java,class,jar}");

        for (Path entry: stream) {

            System.out.println(entry.getName());

        }

    } catch (IOException x) {

        //IOException can never be thrown by the iteration.

        //In this snippet, it can only be thrown by newDirectoryStream.

        System.err.println(x);

    } finally {

        if (stream != null) stream.close()

    }

在 这个例子中,我们只返回以 .java .class .jar结尾的文件或子目录。

我们还可以实现自己的过滤器。例如 如果我们只需要得到所有的子目录,对于文件我们不需要返回,我们就可以编写自己的过滤器。自己的过滤器要实现 DirectoryStream.Filter<T>接口,这个接口只有一个方法 accept,这个方法决定一个文件 /目录是否符合查询条 件。下面是具体的代码:

  1. DirectoryStream.Filter<Path> filter = newDirectoryStream.Filter<Path>() {  
  2.   
  3.     public boolean accept(Path file) {  
  4.   
  5.         try {  
  6.   
  7.             boolean isDirectory = Attributes.readBasicFileAttributes(file).isDirectory();  
  8.   
  9.             return (isDirectory);  
  10.   
  11.         } catch (IOException x) {  
  12.   
  13.             //Failed to determine if it's a directory.  
  14.   
  15.             System.err.println(x);  
  16.   
  17.             return false;  
  18.   
  19.         }  
  20.   
  21.     }  
  22.   
  23. }  
    DirectoryStream.Filter<Path> filter = newDirectoryStream.Filter<Path>() {

        public boolean accept(Path file) {

            try {

                boolean isDirectory = Attributes.readBasicFileAttributes(file).isDirectory();

                return (isDirectory);

            } catch (IOException x) {

                //Failed to determine if it's a directory.

                System.err.println(x);

                return false;

            }

        }

    }


当 过滤器创建好之后,我们可以通过 newDirectoryStream(DirectoryStream.Filter<? super Path>)方法来使用它。下面 就是一个实现的例子:

  1. Path dir = ...;  
  2.   
  3. DirectoryStream<Path> stream = null;  
  4.   
  5. try {  
  6.   
  7.     stream = dir.newDirectoryStream(filter);  
  8.   
  9.     for (Path entry: stream) {  
  10.   
  11.         System.out.println(entry.getName());  
  12.   
  13.     }  
  14.   
  15. catch (IOException x) {  
  16.   
  17.     System.err.println(x);  
  18.   
  19. finally {  
  20.   
  21.     stream.close();  
  22.   

展开
收起
kun坤 2020-06-06 17:13:00 658 0
1 条回答
写回答
取消 提交回答
  • JAVA 7?我没看错,我一直都是用java6的

    ######

    引用来自“罪恶的花生”的帖子

    JAVA 7?我没看错,我一直都是用java6的

    Java 6 没有 java.nio.file.FileSystems 这个东东哦

    ######

    红薯哥,请问JAVA7究竟正式发布没?

    ######

    JAVA7出来了吗? 貌似最新版本是 JDK 6 Update 19 

    ######

    java 7什么时候才能用上

    2020-06-06 17:13:09
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载