zoukankan      html  css  js  c++  java
  • Java—File类详解及实践

    File类介绍

    File类概述

      File类是java.io包下代表与平台无关文件和目录。File可以新建、删除、重命名文件和目录,但是不能访问文件内容本身,如果需要访问内容的话,需要通过输入/输出流进行访问。

      File类可以使用文件路径字符串创建File实例,路径既可以是绝对路径,也可以是相对路径。一般相对路径的话是由系统属性user.dir指定,即为Java VM所在路径。

    File类常用构造器

        /**
         * Creates a new <code>File</code> 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 <code>pathname</code> argument is <code>null</code>
         */
        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对象的所有子文件吗和路径名,返回的是File数组。
    • public boolean mkdir():创建目录,并且只能在已有的父类下面创建子类,如果父类没有,那么就无法创建子类。
    • public boolean mkdirs():也是创建目录,而且可以在父文件夹不存在的情况下,创建子文件夹,顺便将父文件夹也创建了,递归创建。
    • public boolean renameTo(File dest) :重命名此File对象所对应的文件或目录,如果重命名成功,则返回true;否则,返回false。
    • public boolean setReadOnly():设置此File对象为只读权限。
    • public boolean setWritable(boolean writable, boolean ownerOnly):写权限设置,writable如果为true,允许写访问权限;如果为false,写访问权限是不允许的。ownerOnly如果为true,则写访问权限仅适用于所有者;否则它适用于所有人。
    • public boolean setWritable(boolean writable)
      底层实现是:通过setWritable(writable, true)实现,默认是仅适用于文件或目录所有者。
        public boolean setWritable(boolean writable) {
            return setWritable(writable, true);
        }
    
    • public boolean setReadable(boolean readable, boolean ownerOnly):读权限设置,readable如果为true,允许读访问权限;如果为false,读访问权限是不允许的。ownerOnly如果为true,则读访问权限仅适用于所有者;否则它适用于所有人。
    • public boolean setReadable(boolean readable)
      底层实现是:通过setReadable(readable, true)实现,默认是仅适用于文件或目录所有者。
        public boolean setReadable(boolean readable) {
            return setReadable(readable, true);
        }
    
    • public boolean setExecutable(boolean executable, boolean ownerOnly):执行权限设置,executable如果为true,允许执行访问权限;如果为false,执行访问权限是不允许的。ownerOnly如果为true,则执行访问权限仅适用于所有者;否则它适用于所有人。
    • public boolean setExecutable(boolean executable)
      底层实现是:通过setExecutable(executable, true)实现,默认是仅适用于文件或目录所有者。
        public boolean setExecutable(boolean executable) {
            return setExecutable(executable, true);
        }
    
    • public static File[] listRoots():列出系统所有的根路径,可以直接通过File类进行调用。
    • public long getTotalSpace():返回总空间大小,默认单位为字节。
    • public long getFreeSpace():Returns the number of unallocated bytes in the partition,返回未被分配空间大小,默认单位为字节。
    • public long getUsableSpace():Returns the number of bytes available to this virtual machine on the partition,返回可用空间大小,默认单位为字节。
    • public Path toPath():返回该File对象的Path对象。
    • public static File createTempFile(String prefix, String suffix) throws IOException:在默认存放临时文件目录中,创建一个临时空文件。可以直接使用File类来调用,使用给定前缀、系统生成的随机数以及给定后缀作为文件名。prefix至少3字节长。如果suffix设置为null,则默认后缀为.tmp
    • public static File createTempFile(String prefix, String suffix, File directory):在指定的临时文件目录directort中,创建一个临时空文件。可以直接使用File类来调用,使用给定前缀、系统生成的随机数以及给定后缀作为文件名。prefix至少3字节长。如果suffix设置为null,则默认后缀为.tmp

    常用方法示例

    1)运行主类

    package com.example.andya.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    import java.io.File;
    import java.io.IOException;
    import java.net.URI;
    import java.nio.file.Path;
    import java.text.SimpleDateFormat;
    
    
    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) throws IOException {
            File file = new File("C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt");
            System.out.println("getName(): " + file.getName());
            System.out.println("getParent(): " + file.getParent());
            System.out.println("getParentFile(): " + file.getParentFile());
            System.out.println("getAbsolutePath(): " + file.getAbsolutePath());
            System.out.println("getAbsoluteFile(): " + file.getAbsoluteFile());
            System.out.println("getAbsoluteFile().getParent(): " + file.getAbsoluteFile().getParent());
            System.out.println("getPath(): " + file.getPath());
            System.out.println("isAbsolute(): " + file.isAbsolute());
            System.out.println("getCanonicalPath(): " + file.getCanonicalPath());
            System.out.println("getCanonicalFile(): " + file.getCanonicalFile());
            System.out.println("canRead(): " + file.canRead());
            System.out.println("canWrite(): " + file.canWrite());
            System.out.println("canExecute(): " + file.canExecute());
            System.out.println("exists(): " + file.exists());
            System.out.println("isDirectory(): " + file.isDirectory());
            System.out.println("isFile(): " + file.isFile());
            System.out.println("isHidden(): " + file.isHidden());
            System.out.println(file.setLastModified(1546275661));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println("lastModified(): " + simpleDateFormat.format(file.lastModified()));
            //在里面写了"123"这三个数字
            System.out.println("length(): " + file.length());
            File newFile01 = new File("C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest1.txt");
            newFile01.createNewFile();
            newFile01.delete();
    
            File newDir1 = new File("C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\dir1");
            System.out.println("mkdir(): " + newDir1.mkdir());
    
            File newDir2 = new File("C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\dir2\dir2-1");
            System.out.println("mkdirs(): " + newDir2.mkdirs());
    
            String[] fileList = file.getParentFile().list();
            System.out.println("========上一级目录下的所有文件和路径=========");
            for (String fileName : fileList) {
                System.out.println(fileName);
            }
            System.out.println("file重命名:" + file.renameTo(new File("C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt")));
    
            System.out.println("========上一级目录下的所有文件和目录=========");
            File[] files = file.getParentFile().listFiles();
            for (File fileName : files) {
                System.out.println(fileName.getName());
            }
    
            System.out.println("canRead(): " + file.canRead());
    
            //人为改为不可写
            System.out.println("setWritable(): " + file.setWritable(false, false));
            System.out.println("canWrite(): "  + file.canWrite());
    
            System.out.println("canExecute(): " + file.canExecute());
    
    
            System.out.println("========相对路径=========");
            //默认相对路径是user.dir即为当前工程所在位置
            System.out.println("user.dir:" + System.getProperty("user.dir"));
            File newFile = new File("test.txt");
            System.out.println("newFile文件是否存在:" + newFile.exists());
            newFile.createNewFile();
            System.out.println("新建newFile文件后是否存在:" + newFile.exists() + ", 路径为:" + newFile.getAbsolutePath());
            System.out.println("getName(): " + newFile.getName());
            System.out.println("getParent(): " + newFile.getParent());
            System.out.println("getParentFile(): " + newFile.getParentFile());
            System.out.println("getAbsolutePath(): " + newFile.getAbsolutePath());
            System.out.println("getAbsoluteFile(): " + newFile.getAbsoluteFile());
            System.out.println("getAbsoluteFile().getParent(): " + newFile.getAbsoluteFile().getParent());
            System.out.println("getPath(): " + newFile.getPath());
            System.out.println("isAbsolute(): " + newFile.isAbsolute());
            System.out.println("getCanonicalPath(): " + newFile.getCanonicalPath());
            System.out.println("getCanonicalFile(): " + newFile.getCanonicalFile());
            URI uri = newFile.toURI();
            System.out.println("URI:" + uri.toString());
    
            File[] listRoots = File.listRoots();
            System.out.println("========系统根目录下的所有文件和路径=========");
            for (File root : listRoots) {
                System.out.println(root);
            }
    
    
            System.out.println("getTotalSpace(): " + file.getTotalSpace()/1024/1024/1024 + " G");
            System.out.println("getFreeSpace(): " + file.getFreeSpace()/1024/1024/1024 + " G");
            System.out.println("getUsableSpace(): " + file.getUsableSpace()/1024/1024/1024 + " G");
    
            Path path = file.toPath();
            System.out.println("Path: " + path);
    
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }
    
    

    2)运行结果:

    getName(): FileTest.txt
    getParent(): C:UsersLIAOJIANYADesktopfiletestfiledir02
    getParentFile(): C:UsersLIAOJIANYADesktopfiletestfiledir02
    getAbsolutePath(): C:UsersLIAOJIANYADesktopfiletestfiledir02FileTest.txt
    getAbsoluteFile(): C:UsersLIAOJIANYADesktopfiletestfiledir02FileTest.txt
    getAbsoluteFile().getParent(): C:UsersLIAOJIANYADesktopfiletestfiledir02
    getPath(): C:UsersLIAOJIANYADesktopfiletestfiledir02FileTest.txt
    isAbsolute(): true
    getCanonicalPath(): C:UsersLIAOJIANYADesktopfiletestfiledir02FileTest.txt
    getCanonicalFile(): C:UsersLIAOJIANYADesktopfiletestfiledir02FileTest.txt
    canRead(): true
    canWrite(): false
    canExecute(): true
    exists(): true
    isDirectory(): false
    isFile(): true
    isHidden(): false
    true
    lastModified(): 1970-01-19 05:31:15
    length(): 3
    mkdir(): false
    mkdirs(): false
    ========上一级目录下的所有文件和路径=========
    dir1
    dir2
    FileTest.txt
    file重命名:true
    ========上一级目录下的所有文件和目录=========
    dir1
    dir2
    FileTest.txt
    canRead(): true
    setWritable(): true
    canWrite(): false
    canExecute(): true
    ========相对路径=========
    user.dir:C:DATAselfcode
    newFile文件是否存在:true
    新建newFile文件后是否存在:true, 路径为:C:DATAselfcode	est.txt
    getName(): test.txt
    getParent(): null
    getParentFile(): null
    getAbsolutePath(): C:DATAselfcode	est.txt
    getAbsoluteFile(): C:DATAselfcode	est.txt
    getAbsoluteFile().getParent(): C:DATAselfcode
    getPath(): test.txt
    isAbsolute(): false
    getCanonicalPath(): C:DATAselfcode	est.txt
    getCanonicalFile(): C:DATAselfcode	est.txt
    URI:file:/C:/DATA/selfcode/test.txt
    ========系统根目录下的所有文件和路径=========
    C:
    getTotalSpace(): 237 G
    getFreeSpace(): 41 G
    getUsableSpace(): 41 G
    Path: C:UsersLIAOJIANYADesktopfiletestfiledir02FileTest.txt
    

    3)结果的一些验证:
    a)文件长度以及修改时间
    在这里插入图片描述

    b)设置不可写后:
    在这里插入图片描述
    b)磁盘大小
    在这里插入图片描述
    c)user.dir路径
    在这里插入图片描述

    createTempFile临时文件创建示例

    1)运行主类

            File file2 = new File("C:\Users\LIAOJIANYA\Desktop\filetest\filedir01");
            File tmp01 = file2.createTempFile("tmp01", ".tmp");
            File tmp02 = file2.createTempFile("tmp02", ".tmp", file2);
            tmp02.deleteOnExit();
    
            File tmp03 = File.createTempFile("tmp03", null);
            System.out.println("tmp01: " + tmp01.getAbsolutePath());
            System.out.println("tmp02: " + tmp02.getAbsolutePath());
            System.out.println("tmp03: " + tmp03.getAbsolutePath());
    

    2)运行结果

    tmp01: C:UsersLIAOJI~1AppDataLocalTemp	mp01870328708927314810.tmp
    tmp02: C:UsersLIAOJIANYADesktopfiletestfiledir01	mp023046960943790159256.tmp
    tmp03: C:UsersLIAOJI~1AppDataLocalTemp	mp032224782289258299121.tmp
    

    3)查看结果:
    a)默认临时文件存放地址:
    在这里插入图片描述
    b)指定临时文件存放地址:
    在这里插入图片描述
    其中,如果需求中需要创建一个临时文件,这个临时文件可能作为存储使用,但在程序运行结束后需要删除文件,可以使用deleteOnExit()方法。

    FilenameFilter文件过滤器示例

    public String[] list(FilenameFilter filter) 方法的使用。
    1)运行主类

    public class DemoApplication {
    
        public static void main(String[] args) {
            File file = new File("C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\");
            String[] nameArr = file.list(((dir, name) -> name.endsWith(".doc")));
            for (String name : nameArr) {
                System.out.println(name);
            }   
        }
    }
    

    2)运行结果:

    文件01.doc
    

    3)验证:
    在这里插入图片描述
    其中,通过使用Lambda表达式,目标类型为FilenameFilter实现文件过滤,上面过滤了以.doc结尾的文件。

  • 相关阅读:
    k8s service的DNS名称解析之CoreDNS
    k8s service负载均衡实现之iptables
    k8s 将项目暴露到互联网访问
    k8s 日志按体现分类与采集思路
    k8s ingressd的http对外暴露网站
    k8s 容器交付流程和项目部署流程
    k8s ingress使用DaemonSet部署
    Google Base与科学家数据共享 (Nature Vol 438|24 November 2005)
    总结:rdf:ID和rdf:about的区别(转载)
    一个元搜索引擎
  • 原文地址:https://www.cnblogs.com/Andya/p/12698703.html
Copyright © 2011-2022 走看看