file 关闭_JAVA | File类详解及实践

  • Post author:
  • Post category:java


6779a7321a4d35d0604983bf837ae4ba.png



File类介绍




File类概述



File类是

java.io

包下代表

与平台无关



文件和目录

。File可以新建、删除、重命名文件和目录,但是不能访问文件内容本身,如果需要访问内容的话,需要通过

输入/输出流

进行访问。

File类可以使用文件路径字符串创建File实例,路径既可以是绝对路径,也可以是相对路径。一般相对路径的话是由系统属性

user.dir

指定,即为Java VM所在路径。




File类常用构造器



    /**
* Creates a new File instance by converting the given
* pathname string into an abstract pathname. If the given string is
* the empty string, then the result is the empty abstract pathname.
*
* @param pathname A pathname string
* @throws NullPointerException
* If the pathname argument is null
*/
public File(String pathname) {
if (pathname == null) {
throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}




File类常用方法




  • public String getName()

    :返回File对象锁表示的文件名或者目录名(若为目录,返回的是最后一级子目录)。

  • public String getParent()

    :返回此File对象所对应的路径名,返回String类型。

  • public File getParentFile()

    :返回此File对象的父目录,返回File类型。

  • public String getPath()

    :返回此File对象所对应的路径名,返回String类型。

  • public boolean isAbsolute()

    :判断File对象所对应的文件或者目录是否是绝对路径。

  • public String getAbsolutePath()

    :返回此File对象所对应的绝对路径,返回String类型。

  • public String getCanonicalPath() throws IOException


  • public File getCanonicalFile() throws IOException


  • public File getAbsoluteFile()

    :返回此File对象所对应的绝对路径,返回File类型。

  • public boolean canRead()

    :判断此File对象所对应的文件或目录是否可读。

  • public boolean canWrite()

    :判断此File对象所对应的文件或目录是否可写。

  • public boolean canExecute()

    :判断此File对象所对应的文件或目录是否可执行。

  • public boolean exists()

    :判断此File对象所对应的文件或目录是否存在。

  • public boolean isDirectory()

    :判断此File对象是否为目录。

  • public boolean isFile()

    :判断此File对象是否为文件。

  • public boolean isHidden()

    :判断此File对象是否为隐藏。

  • public long lastModified()

    :返回该File对象最后修改的时间戳,我们可以通过

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    进行格式化为时间日期展示。

  • public boolean setLastModified(long time)

    :设置该File对象最后修改的时间戳。

  • public long length()

    :返回该File对象的文件内容长度。

  • public boolean createNewFile() throws IOException

    :当此File对象所对应的文件不存在时,该方法会新建一个该File对象所指定的新文件,如果创建成功,返回true;否则,返回false。

  • public boolean delete()

    :删除File对象所对应的文件或目录,删除成功,返回true;否则,返回false。

  • public void deleteOnExit()

    :Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.意思就是在VM关闭的时候,删除该文件或者目录,不像

    delete()

    方法一调用就删除。一般用于临时文件比较合适。

  • public String[] list()

    :列出File对象的所有子文件名和路径名,返回的是String数组。

  • public File[] listFiles()

    :列出File对象的所有子文件名和路径名,返回