java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java File类方法

Java中File类方法详解以及实践

作者:Andya

Java File类的功能非常强大,利用java基本上可以对文件进行所有操作,下面这篇文章主要给大家介绍了关于Java中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 boolean setWritable(boolean writable) {
        return setWritable(writable, true);
    }
    public boolean setReadable(boolean readable) {
        return setReadable(readable, true);
    }
    public boolean setExecutable(boolean executable) {
        return setExecutable(executable, true);
    }

常用方法示例

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:\Users\LIAOJIANYA\Desktop\filetest\filedir02
getParentFile(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02
getAbsolutePath(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt
getAbsoluteFile(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt
getAbsoluteFile().getParent(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02
getPath(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt
isAbsolute(): true
getCanonicalPath(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.txt
getCanonicalFile(): C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.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:\DATA\selfcode
newFile文件是否存在:true
新建newFile文件后是否存在:true, 路径为:C:\DATA\selfcode\test.txt
getName(): test.txt
getParent(): null
getParentFile(): null
getAbsolutePath(): C:\DATA\selfcode\test.txt
getAbsoluteFile(): C:\DATA\selfcode\test.txt
getAbsoluteFile().getParent(): C:\DATA\selfcode
getPath(): test.txt
isAbsolute(): false
getCanonicalPath(): C:\DATA\selfcode\test.txt
getCanonicalFile(): C:\DATA\selfcode\test.txt
URI:file:/C:/DATA/selfcode/test.txt
========系统根目录下的所有文件和路径=========
C:\
getTotalSpace(): 237 G
getFreeSpace(): 41 G
getUsableSpace(): 41 G
Path: C:\Users\LIAOJIANYA\Desktop\filetest\filedir02\FileTest.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:\Users\LIAOJI~1\AppData\Local\Temp\tmp01870328708927314810.tmp
tmp02: C:\Users\LIAOJIANYA\Desktop\filetest\filedir01\tmp023046960943790159256.tmp
tmp03: C:\Users\LIAOJI~1\AppData\Local\Temp\tmp032224782289258299121.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结尾的文件。

总结

到此这篇关于Java中File类方法详解以及实践的文章就介绍到这了,更多相关Java File类方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文