Java 输入/输出——File类

  File类是java.io包下代表与平台无关的文件和目录,也就是说,如果希望在程序中操作文件和目录,都可以通过File类来完成。值得指出的是,不管是文件还是目录都是使用File来操作的,File能新建、删除、重命名文件和目录,File不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流。

  File类相关的方法参考链接:https://docs.oracle.com/javase/9/docs/api/overview-summary.html

  • Field Summary

    Fields
    Modifier and TypeFieldDescription
    static StringpathSeparator

    The system-dependent path-separator character, represented as a string for convenience.

    static charpathSeparatorChar

    The system-dependent path-separator character.

    static Stringseparator

    The system-dependent default name-separator character, represented as a string for convenience.

    static charseparatorChar

    The system-dependent default name-separator character.

  • Constructor Summary

    Constructors
    ConstructorDescription
    File​(File parent, String child)

    Creates a new File instance from a parent abstract pathname and a child pathname string.

    File​(String pathname)

    Creates a new File instance by converting the given pathname string into an abstract pathname.

    File​(String parent, String child)

    Creates a new File instance from a parent pathname string and a child pathname string.

    File​(URI uri)

    Creates a new File instance by converting the given file: URI into an abstract pathname.

  • Method Summary

    Deprecated Methods
    Modifier and TypeMethodDescription
    booleancanExecute​()

    Tests whether the application can execute the file denoted by this abstract pathname.

    booleancanRead​()

    Tests whether the application can read the file denoted by this abstract pathname.

    booleancanWrite​()

    Tests whether the application can modify the file denoted by this abstract pathname.

    intcompareTo​(File pathname)

    Compares two abstract pathnames lexicographically.

    booleancreateNewFile​()

    Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

    static FilecreateTempFile​(String prefix,String suffix)

    Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

    static FilecreateTempFile​(String prefix,String suffix,File directory)

    Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name.

    booleandelete​()

    Deletes the file or directory denoted by this abstract pathname.

    voiddeleteOnExit​()

    Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

    booleanequals​(Object obj)

    Tests this abstract pathname for equality with the given object.

    booleanexists​()

    Tests whether the file or directory denoted by this abstract pathname exists.

    FilegetAbsoluteFile​()

    Returns the absolute form of this abstract pathname.

    StringgetAbsolutePath​()

    Returns the absolute pathname string of this abstract pathname.

    FilegetCanonicalFile​()

    Returns the canonical form of this abstract pathname.

    StringgetCanonicalPath​()

    Returns the canonical pathname string of this abstract pathname.

    longgetFreeSpace​()

    Returns the number of unallocated bytes in the partition named by this abstract path name.

    StringgetName​()

    Returns the name of the file or directory denoted by this abstract pathname.

    StringgetParent​()

    Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

    FilegetParentFile​()

    Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.

    StringgetPath​()

    Converts this abstract pathname into a pathname string.

    longgetTotalSpace​()

    Returns the size of the partition named by this abstract pathname.

    longgetUsableSpace​()

    Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname.

    inthashCode​()

    Computes a hash code for this abstract pathname.

    booleanisAbsolute​()

    Tests whether this abstract pathname is absolute.

    booleanisDirectory​()

    Tests whether the file denoted by this abstract pathname is a directory.

    booleanisFile​()

    Tests whether the file denoted by this abstract pathname is a normal file.

    booleanisHidden​()

    Tests whether the file named by this abstract pathname is a hidden file.

    longlastModified​()

    Returns the time that the file denoted by this abstract pathname was last modified.

    longlength​()

    Returns the length of the file denoted by this abstract pathname.

    String[]list​()

    Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

    String[]list​(FilenameFilter filter)

    Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

    File[]listFiles​()

    Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

    File[]listFiles​(FileFilter filter)

    Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

    File[]listFiles​(FilenameFilter filter)

    Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

    static File[]listRoots​()

    List the available filesystem roots.

    booleanmkdir​()

    Creates the directory named by this abstract pathname.

    booleanmkdirs​()

    Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.

    booleanrenameTo​(File dest)

    Renames the file denoted by this abstract pathname.

    booleansetExecutable​(boolean executable)

    A convenience method to set the owner's execute permission for this abstract pathname.

    booleansetExecutable​(boolean executable, boolean ownerOnly)

    Sets the owner's or everybody's execute permission for this abstract pathname.

    booleansetLastModified​(long time)

    Sets the last-modified time of the file or directory named by this abstract pathname.

    booleansetReadable​(boolean readable)

    A convenience method to set the owner's read permission for this abstract pathname.

    booleansetReadable​(boolean readable, boolean ownerOnly)

    Sets the owner's or everybody's read permission for this abstract pathname.

    booleansetReadOnly​()

    Marks the file or directory named by this abstract pathname so that only read operations are allowed.

    booleansetWritable​(boolean writable)

    A convenience method to set the owner's write permission for this abstract pathname.

    booleansetWritable​(boolean writable, boolean ownerOnly)

    Sets the owner's or everybody's write permission for this abstract pathname.

    PathtoPath​()

    Returns a java.nio.file.Path object constructed from the this abstract path.

    StringtoString​()

    Returns the pathname string of this abstract pathname.

    URItoURI​()

    Constructs a file: URI that represents this abstract pathname.

    URLtoURL​()

    Deprecated.

    This method does not automatically escape characters that are illegal in URLs. It is recommended that new code convert an abstract pathname into a URL by first converting it into a URI, via the toURImethod, and then converting the URI into a URL via the URI.toURL method.

1、访问文件和目录

 1 package com.zyjhandsome.io;
 2 
 3 import java.io.*;
 4 
 5 public class FileTest {
 6 
 7     public static void main(String[] args) throws IOException
 8     {
 9         // 以当前路径来创建一个File对象
10         File file = new File(".");
11         // 直接获取文件名, 输出一点
12         System.out.println(file.getName());    
13         // 获取相对路径的父路径可能出错, 下面代码输出null
14         System.out.println(file.getParent());
15         // 获取绝对路径
16         System.out.println(file.getAbsoluteFile());
17         // 获取绝对路径
18         System.out.println(file.getAbsoluteFile().getParent());    
19         // 当前路径下创建一个临时文件
20         File tmpFile = File.createTempFile("aaa", ".txt", file);
21         // 指定当JVM退出时候删除该文件
22         tmpFile.deleteOnExit();
23         // 以系统当前时间作为新文件名来创建新文件
24         File newFile = new File(System.currentTimeMillis() + "");
25         System.out.println("newFile对象是否存在1: " + newFile.exists());
26         // 以指定newFile对象来创建一个文件
27         newFile.createNewFile();
28         System.out.println("newFile对象是否存在2: " + newFile.exists());
29         // 以newFile对象来创建一个目录,因为newFile已经存在,所以下面方法返回false, 即无法创建该目录
30         System.out.println("newFile.mkdir():" + newFile.mkdir());
31         System.out.println("----------------------");
32         // 使用list()方法列出当前路径下的所有文件和路径
33         String[] fileList = file.list();
34         for (String fileName : fileList)
35         {
36             System.out.println(fileName);
37         }
38         System.out.println("----------------------");
39         // listRoots()静态方法列出所有的磁盘根路径
40         File[] roots = File.listRoots();
41         System.out.println("====系统所有根路径如下====");
42         for (File root : roots)
43         {
44             System.out.println(root);
45         }
46     }
47 }
 1 .
 2 null
 3 D:\zhaoyingjun\eclipse-workspace\CollectionTest\.
 4 D:\zhaoyingjun\eclipse-workspace\CollectionTest
 5 newFile对象是否存在1: false
 6 newFile对象是否存在2: true
 7 newFile.mkdir():false
 8 ----------------------
 9 .classpath
10 .project
11 .settings
12 1537712414564
13 1537712424492
14 1537712893895
15 1537712926829
16 1537712940906
17 1537713158525
18 1537713167968
19 1537774060515
20 aaa1610208071466755969.txt
21 bin
22 src
23 ----------------------
24 ====系统所有根路径如下====
25 C:\
26 D:\

2、文件过滤器

  在File类的list()方法中可以接收一个FilenameFilter参数,通过该参数可以只列出符合条件的文件。这里的FilenameFilter接口和javax.swing.filechooser包下的FileFilter抽象类的功能非常相似,可以把FileFilter当成是FilenameFilter的实现类。

  FilenameFilter接口里包含了一个accept(File dir, String name)方法,该方法将依次对指定File的所有子目录或者文件进行迭代,如果该方法返回true,则list()方法会列出该子目录或者文件。

 1 package com.zyjhandsome.io;
 2 
 3 import java.io.*;
 4 
 5 public class FilenameFilterTest {
 6 
 7     public static void main(String[] args) {
 8         // TODO Auto-generated method stub
 9         File file = new File(".");
10         // 使用Lambda表达式(目标类型是FilenameFilter)实现文件过滤器
11         // 如果文件名以.java结尾, 或者文件对应一个路径,则返回true
12         String[] nameList = file.list((dir, name) ->
13             name.endsWith(".java") || new File(name).isDirectory());
14         for (String name : nameList)
15         {
16             System.out.println(name);
17         }                
18     }    
19 }
1 .settings
2 bin
3 src