一、概述

在整个 Java.io 中最重要的就是5个类和一个接口。5个类指的是 File、InputStream、OutputStream、Reader、Writer,一个接口指的是Serializable。掌握了这些IO的核心操作那么对于Java中的IO体系也就有了一个初步的认识了。

  • File(文件类):主要用来描述文件或目录的属性,例如:文件大小,修改文件名,删除文件,判断文件所在路径等。
  • InputStream(字节输入流):抽象类,基于字节的输入操作,是所有输入流的父类。定义了所有输入流都具有的共同特征。
  • OutputStream(字节输出流):抽象类。基于字节的输出操作。是所有输出流的父类。定义了所有输出流都具有的共同特征。
  • Reader(输入流):抽象类,基于字符的输入操作。
  • Writer(输出流):抽象类,基于字符的输出操作。
  • Serializable():

二、File 类

从定义看,File类是Object的直接子类,同时它继承了Comparable接口可以进行数组的排序。File 类的操作包括文件的创建、删除、重命名、得到路径、创建时间等,以下是文件操作常用的函数。

Java学习之==>IO文件操作体系

File类是对文件系统中文件以及文件夹进行封装的对象,可以通过对象的思想来操作文件和文件夹。File类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间、是否可读、获取当前文件的路径名,判断指定文件是否存在、获得当前目录中的文件列表,创建、删除文件和目录等方法。

private static void demo01() {
  File file = new File("/course/test.log");

  boolean canRead = file.canRead();
  System.out.println("canRead = " + canRead);

  boolean canWrite = file.canWrite();
  System.out.println("canWrite = " + canWrite);

  boolean canExecute = file.canExecute();
  System.out.println("canExecute = " + canExecute);

  file.setReadable(true);

  canRead = file.canRead();
  System.out.println("canRead = " + canRead);
}

private static void demo02() {
  File file = new File("/course/test.log");
  String fileName = file.getName();
  System.out.println("fileName = " + fileName);

  File fileAbsoluteFile = file.getAbsoluteFile();
  System.out.println("fileAbsoluteFile = " + fileAbsoluteFile);

  String fileAbsolutePath = file.getAbsolutePath();
  System.out.println("fileAbsolutePath = " + fileAbsolutePath);

  String fileParent = file.getParent();
  System.out.println("fileParent = " + fileParent);

  File fileParentFile = file.getParentFile();
  System.out.println("fileParentFile = " + fileParentFile);

  String filePath = file.getPath();
  System.out.println("filePath = " + filePath);
}

private static void demo03() {
  File file = new File("/course");
  System.out.println("file.isFile() = " + file.isFile());
  System.out.println("file.isDirectory() = " + file.isDirectory());
}

private static void demo04() {
  File file = new File("/course/test.log");

  final boolean exists = file.exists();
  System.out.println("exists = " + exists);

  boolean canRead = file.canRead();
  System.out.println("canRead = " + canRead);

  boolean canWrite = file.canWrite();
  System.out.println("canWrite = " + canWrite);

  boolean canExecute = file.canExecute();
  System.out.println("canExecute = " + canExecute);

  boolean isFile = file.isFile();
  System.out.println("isFile = " + isFile);

  boolean isDir = file.isDirectory();
  System.out.println("isDir = " + isDir);
}
文件属性操作

相关文章:

  • 2021-10-10
  • 2021-05-30
  • 2022-01-19
  • 2021-12-06
  • 2021-09-06
  • 2022-12-23
  • 2021-09-17
猜你喜欢
  • 2022-12-23
  • 2021-11-02
  • 2021-05-22
  • 2020-10-07
  • 2021-07-22
  • 2022-12-23
  • 2022-02-03
相关资源
相似解决方案