Java IO 学习总结(二)File 类

Java IO 学习总结(一)输入流/输出流
Java IO 学习总结(二)File 类
Java IO 学习总结(三)BufferedInputStream
Java IO 学习总结(四)BufferedReader 缓冲字符流
Java IO 学习总结(五)OutputStreamWriter

前言:

学习IO流,记录并分享。文章如有错误,恳请指正。

Java IO 学习总结(二)

在这里插入图片描述

1.什么是 Java File 类,为什么要使用 File 类?

在 Java 中,File 类是 java.io 包中唯一代表磁盘文件本身的对象。File 类定义了一些与平台无关的方法来操作文件,File类主要用来获取或处理与磁盘文件相关的信息,像文件名、 文件路径、访问权限和修改日期等,还可以浏览子目录层次结构。但不支持写入信息或读取信息文件的功能,它仅描述文件本身的属性。写入或读取的操作由IO流完成。

2.File 类中的构造方法源码

/**
 * Internal constructor for already-normalized pathname strings.
 */
private File(String pathname, int prefixLength) {
    this.path = pathname;
    this.prefixLength = prefixLength;
}

/**
 * Internal constructor for already-normalized pathname strings.
 * The parameter order is used to disambiguate this method from the
 * public(File, String) constructor.
 */
private File(String child, File parent) {
    assert parent.path != null;
    assert (!parent.path.equals(""));
    this.path = fs.resolve(parent.path, child);
    this.prefixLength = parent.prefixLength;
}

/**
 * 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);
}

/**
 * Creates a new <code>File</code> instance from a parent pathname string
 * and a child pathname string.
 
 * @param   parent  The parent pathname string
 * @param   child   The child pathname string
 * @throws  NullPointerException
 *          If <code>child</code> is <code>null</code>
 */
public File(String parent, String child) {
    if (child == null) {
        throw new NullPointerException();
    }
    if (parent != null) {
        if (parent.equals("")) {
            this.path = fs.resolve(fs.getDefaultParent(),
                                   fs.normalize(child));
        } else {
            this.path = fs.resolve(fs.normalize(parent),
                                   fs.normalize(child));
        }
    } else {
        this.path = fs.normalize(child);
    }
    this.prefixLength = fs.prefixLength(this.path);
}

/**
 * Creates a new <code>File</code> instance from a parent abstract
 * pathname and a child pathname string.
 *
 * <p> If <code>parent</code> is <code>null</code> then the new
 * <code>File</code> instance is created as if by invoking the
 * single-argument <code>File</code> constructor on the given
 * <code>child</code> pathname string.
 *
 * @param   parent  The parent abstract pathname
 * @param   child   The child pathname string
 * @throws  NullPointerException
 *          If <code>child</code> is <code>null</code>
 */
public File(File parent, String child) {
    if (child == null) {
        throw new NullPointerException();
    }
    if (parent != null) {
        if (parent.path.equals("")) {
            this.path = fs.resolve(fs.getDefaultParent(),
                                   fs.normalize(child));
        } else {
            this.path = fs.resolve(parent.path,
                                   fs.normalize(child));
        }
    } else {
        this.path = fs.normalize(child);
    }
    this.prefixLength = fs.prefixLength(this.path);
}

/**
 * Creates a new <tt>File</tt> instance by converting the given
 * <tt>file:</tt> URI into an abstract pathname.
 *
 * @param  uri
 *         An absolute, hierarchical URI with a scheme equal to
 *         <tt>"file"</tt>, a non-empty path component, and undefined
 *         authority, query, and fragment components
 *
 * @throws  NullPointerException
 *          If <tt>uri</tt> is <tt>null</tt>
 *
 * @throws  IllegalArgumentException
 *          If the preconditions on the parameter do not hold
 *
 * @see #toURI()
 * @see java.net.URI
 * @since 1.4
 */
public File(URI uri) {
    // Check our many preconditions
    if (!uri.isAbsolute())
        throw new IllegalArgumentException("URI is not absolute");
    if (uri.isOpaque())
        throw new IllegalArgumentException("URI is not hierarchical");
    String scheme = uri.getScheme();
    if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
        throw new IllegalArgumentException("URI scheme is not \"file\"");
    if (uri.getAuthority() != null)
        throw new IllegalArgumentException("URI has an authority component");
    if (uri.getFragment() != null)
        throw new IllegalArgumentException("URI has a fragment component");
    if (uri.getQuery() != null)
        throw new IllegalArgumentException("URI has a query component");
    String p = uri.getPath();
    if (p.equals(""))
        throw new IllegalArgumentException("URI path component is empty");
    // Okay, now initialize
    p = fs.fromURIPath(p);
    if (File.separatorChar != '/')
        p = p.replace('/', File.separatorChar);
    this.path = fs.normalize(p);
    this.prefixLength = fs.prefixLength(this.path);
}

从源码可以看出 File 类的构造方法有6个,精简如下:

// 这两个是File类中私有的构造函数,外面不能调用
private File(String child, File parent);  
private File(String pathname, int prefixLength); 

/**
 * File 类的4个公共的构造方法
 */
private static void testFileConstructor() {
    // 1.new File(URI uri)  // 文件的URI地址, 可以通过 url 文件地址创建 File 对象
    // 2.通过路径名创建一个新 File 实例
    File constructor = new File("D:/test/success/newFile.txt");

    // 3.根据父路径名和子路径名来创建一个新的 File 实例
    File constructor1 = new File(new File("D:/test/ccc"), "/bb/newFile.txt");

    // 4.根据父路径名和子路径名创建一个新的 File 实例
    File constructor2 = new File("D:/test/ccc", "newFile.txt"); 

    // ================ 运行结果 ================
    // toString() 打印结果: D/test/success/newFile.txt
    System.out.println("constructor = " + constructor);
    // toString() 打印结果: D\test\ccc\bb\newFile.txt
    System.out.println("constructor1 = " + constructor1);
    // toString() 打印结果: D\test\ccc\newFile.txt
    System.out.println("constructor2 = " + constructor2);
}

6个构造函数,可以分为2类。4个公共构造函数,2个私有构造函数。

3.File 类的公共 Api 方法:

/**
 * File 类其它的公共 Api 方法
 */
private static void otherFileApi() {
    // 通过路径名创建一个新 File 实例
    File file = new File("D:/test/testName.txt");

    File parentFile = file.getParentFile(); // 此 Api 方法返回的是一个父目录 File 实例对象
    String parent = file.getParent(); // 返回此路径名的父目录的路径名字符串
    String path = file.getPath(); // 返回当前文件的绝对路径
    String fileName = file.getName(); // 返回文件名称字符串
    boolean directory = file.isDirectory(); // 是否是目录
    boolean absolute = file.isAbsolute(); // 是否为绝对路径
    boolean hidden = file.isHidden(); // 是否隐藏(windows上可以设置某个文件是否隐藏)
    boolean exists = file.exists(); // 文件是否存在
    boolean isFile = file.isFile(); // 是否是文件
    boolean canRead = file.canRead(); // 是否可读
    boolean canWrite = file.canWrite(); // 是否可写
    boolean canExecute = file.canExecute(); // 是否可执行

    // ================ 运行结果 ================
    // D\test
    System.out.println("parentFile = " + parentFile);
    // D\test
    System.out.println("parent = " + parent);
    // D\test\testName.txt
    System.out.println("path = " + path);
    // testName.txt
    System.out.println("fileName = " + fileName);
    // false
    System.out.println("directory = " + directory);
    // true
    System.out.println("absolute = " + absolute);
    // false
    System.out.println("hidden = " + hidden);
    // true
    System.out.println("exists = " + exists);
    // true
    System.out.println("isFile = " + isFile);
    // true
    System.out.println("canRead = " + canRead);
    // true
    System.out.println("canWrite = " + canWrite);
    // true
    System.out.println("canExecute = " + canExecute);
}

4、实战:

(1)在指定文件路径上创建目录

/**
 * 创建一个目录和其中的文件
 *
 * @param directoryPath 要创建目录的路径
 * @param fileName      要创建的文件的名称
 * @throws IllegalArgumentException 如果directoryPath或fileName为空
 * @throws IOException              如果在创建文件时发生IO错误。
 */
public static void createDirectoryAndFile(String directoryPath, String fileName)
        throws IllegalArgumentException, IOException {
    if (StringUtils.isEmpty(directoryPath) || StringUtils.isEmpty(fileName)) {
        throw new IllegalArgumentException("目录的路径或fileName创建的文件的名称为空");
    }
    File directory = new File(directoryPath);
    // 判断有没有这个文件夹,没有则创建
    if (!directory.isDirectory()) {
        directory.mkdirs();
    }
    File file = new File(directory, fileName);
    // 如果文件创建成功,则为True,否则为false。
    System.out.println("file.createNewFile() = " + file.createNewFile());
}

(2)打印指定目录中所有文件的名称

/**
 * 打印指定目录中所有文件的名称
 *
 * @param directoryPath 目录路径
 * @throws NotDirectoryException 如果指定的路径不是目录
 * @throws IOException           如果在访问目录时发生IO错误
 */
public static void listFiles(String directoryPath) throws NotDirectoryException, IOException {
    File directory = new File(directoryPath);
    if (!directory.isDirectory()) {
        throw new NotDirectoryException("无效目录的路径: " + directoryPath);
    }
    File[] files = directory.listFiles();
    if (files == null) {
        throw new IOException("访问目录失败:" + directoryPath);
    }
    for (File file : files) {
        if (file.isFile()) {
            System.out.println(file.getName());
        }
    }
}

(3)打印指定目录中的所有文件名与文件夹名称到控制台中

/**
 * 打印指定目录中的所有文件名与文件夹名称到控制台中
 *
 * @param filePath 目录路径
 * @throws NotDirectoryException 如果指定的路径不是目录
 * @throws IOException           如果在访问目录时发生IO错误
 */
public static void fileList(String filePath) throws IOException {
    File file = new File(filePath);
    if (!file.isDirectory()) {
        throw new NotDirectoryException("无效的路径,不存在当前文件夹!" + filePath);
    }
    String[] fileName = file.list(); // 返回目录下所有的文件名称
    if (fileName == null) {
        throw new IOException("该路径无效,没有找到文件");
    }
    for (String name : fileName) {
        System.out.println("fileName: " + name);
    }
}

(4)打印指定目录中所有文件的名称,使用过滤器 MyFileFilter 过滤文件夹

/**
 * 打印指定目录中所有文件的名称,使用过滤器 MyFileFilter 过滤掉文件夹名称。
 *
 * @param directoryPath 目录路径
 * @throws NotDirectoryException 如果指定的路径不是目录
 * @throws IOException           如果在访问目录时发生IO错误
 */
public static void fileListFilter(String directoryPath) throws IOException {
    MyFileFilter fileFilter = new MyFileFilter();
    File file = new File(directoryPath);
    if (!file.isDirectory()) {
        throw new NotDirectoryException("无效的路径,不存在当前文件夹!" + directoryPath);
    }
    File[] files = file.listFiles(fileFilter);// 返回目录下所有的文件名称
    if (files == null) {
        throw new IOException("该路径无效,没有找到文件");
    }
    for (File temp : files) {
        System.out.println(temp.getName());
    }
}

FileFilter 过滤类实现

package com.io.file;

import java.io.File;
import java.io.FileFilter;

public class MyFileFilter implements FileFilter {

    public MyFileFilter() {

    }

    //pathname:文件的绝对路径 + 文件名 , 比如:F:\安来宁 - 难得.mp3  , 或者: F:\文件夹1
    @Override
    public boolean accept(File pathname) {
        if (pathname.isDirectory()) {
            return false;
        }
        return true;
    }

}

Java IO 学习总结(六) 正在完善中,后续更新~


猜你喜欢

转载自blog.csdn.net/uziuzi669/article/details/131193859