【Java IO流】流的分类,API使用,文件操作

简介: 【Java IO流】流的分类,API使用,文件操作


中秋特供啦 🥮

提前祝大家 中秋 | 国庆 快乐 🥮🥮🥮

Java Io 🍔

什么是流

I: Input | 输入

O: Output | 输出

流的分类

  • 按照数据的流向
  • 输入流:读数据
  • 输出流:写数据
  • 按照数据类型来分
  • 字节流
  • 字节输入流
  • 字节输出流
  • 字符流
  • 字符输入流
  • 字符输出流

输入流,输出流

字节流,字符流

文件字节输入流

FileInputStream

package FileInput;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
 * Author: _LJaXi
 * @author ASUS
 */
class FileInput {
    public static void main(String[] args) throws IOException {
        try {
            FileInputStream fis = new FileInputStream("d:\\aaa.txt");
            // 一次读取多个字节,存到数组中
            // 创建一个长度为3的数组 / 字节类型
            byte[] buf = new byte[3];
            int count = 0;
            // 条件判断循环
            while ((count = fis.read(buf)) != -1) {
                System.out.print(new String(buf,0,count));
            }
            // 3. 关闭
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

1. 条件循环解决

package main.java.com.mycode;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
 * Author: _LJaXi
 * @author ASUS
 */
class MyIo {
  public static void main(String[] args) throws IOException {
    try {
      FileInputStream fis = new FileInputStream("d:\\aaa.txt");
      // 读取
      System.out.println(fis.read());
      int data = 0;
      // 循环打印字节
      while ((data = fis.read()) != -1) {
        System.out.print((char) data);
      }
      // 3. 关闭
      fis.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
}
1 (2) 读取特性
package main.java.com.mycode;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
 * Author: _LJaXi
 * @author ASUS
 */
class MyIo {
  public static void main(String[] args) throws IOException {
    try {
      FileInputStream fis = new FileInputStream("d:\\aaa.txt");
      // 一次读取多个字节,存到数组中
      // 创建一个长度为3的数组 / 字节类型
      byte[] buf = new byte[3];
      // 返回实例读取的个数
      int count = fis.read(buf);
      // 打印字符串 buf
      System.out.println(new String(buf));
      System.out.println(count);
      // 多次读取
      int count2 = fis.read(buf);
      System.out.println(new String(buf));
      System.out.println(count2);
      int count3 = fis.read(buf);
      System.out.println(new String(buf));
      System.out.println(count3);
      // 若文件内字符太短,可能会出现读取数组you多余元素问题,那是你的上次buf数组没有清空导致的
      // 可以使用
      // System.out.println(new String(buf, index(索引), count3)); 来清理多余的元素
      // new String(buf)参数:
      // 1. param1 是一个字节数组,用于构建新的字符串对象
      // 2. param2 是偏移量(offset),表示从 param1 的索引为 param2 的位置开始构建字符串
      // 3. param3 是长度(length),表示构建字符串的长度
      // 3. 关闭
      fis.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
}

2. 数组存储解决

package main.java.com.mycode;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
 * Author: _LJaXi
 * @author ASUS
 */
class MyIo {
  public static void main(String[] args) throws IOException {
    try {
      FileInputStream fis = new FileInputStream("d:\\aaa.txt");
      // 一次读取多个字节,存到数组中
      // 创建一个长度为3的数组 / 字节类型
      byte[] buf = new byte[3];
     int count = 0;
     // 条件判断循环
     while ((count = fis.read(buf)) != -1) {
         System.out.print(new String(buf,0,count));
     }
      // 3. 关闭
      fis.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
}

文件字节输出流

FileOutputStream

package main.java.com.mycode;
import java.io.FileOutputStream;
/**
 * Author: _LJaXi
 * @author ASUS
 */
public class FileOutput {
  public static void main (String[] args) throws Exception {
    // 1. 创建文件字节输出流对象
    // 若不想覆盖原本内容,将构造方法append,设置为true
    FileOutputStream fos = new FileOutputStream("d://aaa.txt", true);
    // 2. 写入文件
    // fos.write(97);
    // fos.write('b');
    // fos.write('c');
    String str = "helloworld";
    // 获取字符串所对应的字节数组
    fos.write(str.getBytes());
    // 3. 关闭
    fos.close();
    System.out.println("执行完毕");
  }
}
输出流构造方法
// 某个构造方法有个形参 append,这个构造方法的 append 若为true 表明不覆盖原本内容
public FileOutputStream(String name, boolean append)
        throws FileNotFoundException
    {
        this(name != null ? new File(name) : null, append);
    }

字节流复制文件

package CopyFile;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* 使用文件字节流实现文件的复制
* */
public class CopyFile {
    public static void main(String[] args) throws IOException {
        // 1. 先用文件字节输入流读到内存中
        FileInputStream fis = new FileInputStream("C:\\Users\\ASUS\\Desktop\\凌波.png");
        // 2. 再用一个文件字节输出流写入到硬盘
        FileOutputStream fos = new FileOutputStream("C:\\Users\\ASUS\\Desktop\\凌波丽.jpg");
        // 3. 一边读 一边写
        byte[] buf = new byte[1024];
        int count = 0;
        while((count=fis.read(buf)) != -1) {
            fos.write(buf,0,count);
        }
        // 4. 关闭流
        fis.close();
        fos.close();
        System.out.print("复制完毕");
    }
}

字节缓冲流

BufferedInputStream / Buffered0utputStream

提高IO效率,减少访问磁盘的次数;

数据存储在缓冲区中,flush是将缓存区的内容写入文件中,也可以直接close;

BufferedInputStream

package Buffered;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
/*
* 使用字节缓冲流读取
* BufferedInputStream
* @Tip 我想和 符韬_(pinegg) 一起玩
* */
public class BufferedStream {
    public static void main(String[] args) throws IOException {
        // 1. 创建BufferedInputStream
        FileInputStream fis = new FileInputStream("d:\\aaa.txt");
        // 增强底层流
        BufferedInputStream bis = new BufferedInputStream(fis);
        // 2. 读取 bis 读文件会放在缓冲区,提高效率
        int count = 0;
        // bis.read() 并不是读一个字节,先把一部分数据读到bis缓冲区内,调用已经读了8k了
        // private static int DEFAULT_BUFFER_SIZE = 8192;
        while ((count=bis.read()) != -1) {
            System.out.print((char) count);
        }
        // 3. 关闭
        bis.close(); // 缓冲流close之后, 会自动帮你关闭输入流 fis.close()
    }
}

BufferedInputStream 自定义读取部分数据

package Buffered;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
/*
* 使用字节缓冲流读取
* BufferedInputStream
* @author 符韬是谁?
* */
public class BufferedStream {
    public static void main(String[] args) throws IOException {
        // 1. 创建BufferedInputStream
        FileInputStream fis = new FileInputStream("d:\\aaa.txt");
        // 增强底层流
        BufferedInputStream bis = new BufferedInputStream(fis);
        // 2. 读取 bis 读文件会放在缓冲区,提高效率
        int count = 0;
        // bis.read() 并不是读一个字节,先把一部分数据读到bis缓冲区内,调用已经读了8k了
        // private static int DEFAULT_BUFFER_SIZE = 8192;
        // 当然你也可以自己定义把一部分数据读取到缓冲区, 下方注释写法
        byte[] buf = new byte[6000];
        while ((count=bis.read(buf)) != -1) {
            System.out.print(new String(buf, 0, count));
        }
        // 3. 关闭
        bis.close(); // 缓冲流close之后, 会自动帮你关闭输入流 fis.close()
    }
}

BufferedOutputStream

package Buffered;
import java.io.*;
/*
 * 使用字节缓冲流写入
 * BufferedOutputStream
 * @time 2023年9月11日14:19:47
 * @author _LJaXi
 * @tip 想秀阿卡丽
 * */
public class OutputStream {
    public static void main(String[] args) {
        try {
            FileOutputStream fos = new FileOutputStream("d:\\aaa.txt", true);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            String data = "LOL";
            bos.write(data.getBytes()); // 写入 8k 到缓冲区
            fos.flush(); // 刷新到硬盘
            /*---------------------------------------------------------------
            * bos.flush()的作用是将缓冲区中的数据立即刷新(写入)到硬盘中
            * 当使用BufferedOutputStream写入数据时,数据通常会先被存储在内部的缓冲区中,直到缓冲区达到一定的容量或者手动调用flush()方法
            * ---------------------------------------------------------------
            * flush()方法的使用是为了确保数据被及时写入硬盘,而不是一直停留在缓冲区
            * 在调用flush()方法后,任何未写入的数据将被立即写入到硬盘中,这样可以避免数据丢失的风险
            * ---------------------------------------------------------------
            * 在流关闭之前或发生异常时,也会自动调用flush()方法,确保所有数据都被写入硬盘
            * ---------------------------------------------------------------*/
            bos.close(); // 内部也会调用 flush() 方法
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

对象流

  1. 增强了缓冲区功能
  2. 增强了读写8种基本数据类型和字符串功能
  3. 增强了读写对象的功能 {

readObject() 从流中读取一个对象

writeObject(Object obj) 向流中写入一个对象

}

使用流传输对象的过程称为序列化(写入)、反序列化(读取)

Student 类

package ObjectStream;
import java.io.Serializable;
// 要想序列化,类必须实现一个接口,为标记接口
public class Student implements Serializable {
    private String name;
    private int age;
    public Student() {
    }
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    // this is 重写 toString 方法
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

ObjectOutStream

package ObjectStream;
import java.io.*;
/*
* 序列化类必须要实现 Serializable 接口(标记接口)
* ObjectOutputStream
* @time 2023年9月14日13:49:52
* @author _LJaXi
* @tip 阿卡丽5连败
* */
public class OutStream {
    public static void main(String[] args)throws IOException {
        // 1. 创建对象流
        FileOutputStream fos = new FileOutputStream("d:\\aaa.bin");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        // 2. 序列化(写入操作)
        Student zs = new Student("张三", 20);
        oos.writeObject(zs);
        // 3. 关闭
        oos.close();
        System.out.println("序列化完毕");
    }
}

ObjectInputSteam

package ObjectStream;
import java.io.*;
/*
* ObjectInputStream 反序列化(读取重构成对象)
* @time 2023年9月14日23:31:23
* @author _LJaXi
* @tip 阿卡丽排位3连胜
* */
public class InputStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 1. 创建对象流
        FileInputStream fis = new FileInputStream("d:\\aaa.bin");
        ObjectInputStream ois = new ObjectInputStream(fis);
        // 2. 读取文件(反序列化)
        Student s = (Student)ois.readObject();
        // Student s2 = (Student)ois.readObject(); // 不能读取多次
        // 3. 关闭
        ois.close();
        System.out.println("执行完毕");
        System.out.println(s.toString());
    }
}
序列化和反序列化注意点

序列化类必须实现 Serializable 接口

序列化类中对象属性要求实现 Serializable 接口

序列化类中对象属性要求实现 Serializable 接口意思为:

public class Student implements Serializable {
    private String name;
    private int age;
    private Class class; // Class类要实现 Serializable 接口
    // ... 其他内容
}
serialVersionUlD 警告

警告: 添加一个 serialVersionUlD 常量(Java内置,可在设置中打开)

The serializable class Student does not declare a static final serialVersionUlD field of type long

在类中添加:

private static final long serialVersionUID = 100L;

意义: 序列化版本号ID

作用:保证序列化的类和反序列化的类是同一个类

对于没有显式声明 serialVersionUID 的类,Java会自动生成一个默认值

transient 禁止序列化某属性

若不相信序列化类中的某个属性,可使用 transient(瞬间的, 瞬时的) 关键字修饰

// Student
package ObjectStream;
import java.io.Serializable;
public class Student implements Serializable {
    private String name;
    private transient int age; // age禁止被序列化
    public Student() {
    }
    // ....其他操作
}
序列化读取多次

序列化可写入多个对象,在反序列化时读取多个即可

// 序列化
public class OutStream {
    public static void main(String[] args)throws IOException {
        // 1. 创建对象流
        FileOutputStream fos = new FileOutputStream("d:\\aaa.bin");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        // 2. 序列化(写入操作)
        Student zs = new Student("张三", 20);
        Student ls = new Student("李四", 20); // 定义ls对象 ⭕
        oos.writeObject(zs);
        oos.writeObject(ls); // 写入ls ⭕
        // 3. 关闭
        oos.close();
        System.out.println("序列化完毕");
    }
}
// 反序列化
public class InputStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 1. 创建对象流
        FileInputStream fis = new FileInputStream("d:\\aaa.bin");
        ObjectInputStream ois = new ObjectInputStream(fis);
        // 2. 读取文件(反序列化)
        Student s = (Student)ois.readObject();
        Student s2 = (Student)ois.readObject(); // 读取多次 ⭕
        // 3. 关闭
        ois.close();
        System.out.println("执行完毕");
        System.out.println(s.toString());
    }
}
借助集合实现多个对象的序列化
// 序列化
public class OutStream {
    public static void main(String[] args)throws IOException {
        // 1. 创建对象流
        FileOutputStream fos = new FileOutputStream("d:\\aaa.bin");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        ArrayList<Student> list = new ArrayList<>(); // ⭕定义集合
        // 2. 序列化(写入操作)
        Student zs = new Student("张三", 20);
        Student ls = new Student("李四", 20);
        // ⭕ 添加元素
        list.add(zs);
        list.add(ls);
        oos.writeObject(list); // ⭕写入
        // oos.writeObject(zs);
        // oos.writeObject(ls);
        // 3. 关闭
        oos.close();
        System.out.println("序列化完毕");
    }
}
// 反序列化
public class InputStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 1. 创建对象流
        FileInputStream fis = new FileInputStream("d:\\aaa.bin");
        ObjectInputStream ois = new ObjectInputStream(fis);
        // 2. 读取文件(反序列化)
        ArrayList<Student> l = (ArrayList<Student>) ois.readObject();  // ⭕强转
        // Student s = (Student)ois.readObject();
        // Student s2 = (Student)ois.readObject();
        // 3. 关闭
        ois.close();
        System.out.println("执行完毕");
        // System.out.println(s.toString());
        System.out.println(list.toString()); // ⭕打印
    }
}

字符流

字符流以字符为单位读写数据,提供了更高层次的操作,能够方便地处理文本数据

文件字符输入流 FileReader

package FileReaderAndWriter;
import java.io.FileReader;
public class FileRead {
    public static void main(String[] args)throws Exception {
        // 1. 创建 FileReader 文件字符输入流
        FileReader fr = new FileReader("d:\\aaa.txt");
        // 2. 读取
        // int data = 0;
        // while((data = fr.read()) != -1) {
        //     System.out.print((char) data);
        // }
        // 创建缓冲区
        char[] buf = new char[1024];
        int count = 0;
        while((count = fr.read(buf)) != -1) {
            System.out.print(new String(buf, 0, count));
        }
        // 3. 关闭
        fr.close();
    }
}

文件字符输出流 FileWriter

package FileReaderAndWriter;
import java.io.FileWriter;
public class FileWrite {
    public static void main(String[] args)throws Exception {
        // 1. 创建文件字符输出流
        FileWriter fw = new FileWriter("d:\\write.txt");
        // 2. 写入
        for (int i = 0; i < 10; i++) {
            fw.write("Java是世界上最好的语言\r\n"); // 换行写入 \r\n
            fw.flush();
        }
        // 3. 关闭
        fw.close();
    }
}

使用 FileReaderFileWriter 复制文本文件

package FileReaderAndWriter;
import java.io.FileReader;
import java.io.FileWriter;
/*
* 使用 FileReader 和 FileWriter 复制文本文件,不能复制图片或者二进制文件
* =============== 使用字节流才可以复制任何文件 =================
* @author _LJaXi
* */
public class CopyFile {
    public static void main(String[] args)throws Exception {
        // 1. 创建 FileReader FileWriter
        FileReader fr = new FileReader("d://write.txt");
        FileWriter fw = new FileWriter("d://write2.txt");
        // 2. 读写
        int data = 0;
        while((data = fr.read()) != -1) {
            fw.write(data);
        }
        // 3. 关闭
        fr.close();
        fw.close();
        System.out.println("执行完毕");
    }
}

字符缓冲流 BufferedReader \ BufferedWriter

高效读取, 高效写入

字符缓冲流读取文件 BufferedReader
package FileReaderAndWriter;
import java.io.BufferedReader;
import java.io.FileReader;
/*
* 使用字符缓冲流读取文件
* 高效读取
* BufferedReader
* */
public class BufferedReaderStream {
    public static void main(String[] args)throws Exception {
        // 1. 创建缓冲流
        FileReader fr = new FileReader("d:\\write.txt");
        BufferedReader br = new BufferedReader(fr);
        // 2. 读取
        // char[] buf = new char[1024];
        // int count = 0;
        // while ((count = br.read(buf)) != -1) {
        //     System.out.println(new String(buf, 0, count));
        // }
        // 2.1 第二种方式 一行一行的读取
        // readLine() BufferedReader提供的API
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        // 3. 关闭
        br.close();
    }
}
字符缓冲流写入文件 BufferedWriter
package FileReaderAndWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
/*
* 字符缓冲流
* BufferedWriter
* */
public class BufferedWriterStream {
    public static void main(String[] args)throws Exception {
        FileWriter fw = new FileWriter("d:\\buffer.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        // 2. 写入
        for (int i = 0; i < 10; i++) {
            bw.write("好好学习。");
            bw.newLine(); // 换行符,等同于 \r\n
            bw.flush();
        }
        // 3. 关闭
        bw.close();
    }
}

打印流

package PrintWriterStream;
import java.io.PrintWriter;
/*
* PrintWriter
* */
public class Print {
    public static void main(String[] args)throws Exception {
        // 1. 新建 打印流
        PrintWriter pw = new PrintWriter("d:\\print.txt");
        // 2. 打印
        pw.println(97);
        pw.println(true);
        pw.println(3.14);
        pw.println('a');
        // 3. 关闭
        pw.close();
    }
}

转换流

InputStreamReaderOutputStreamWriter 是用于处理字符流(文本)的桥接类, 它们将字节流转换为字符流

使用 InputStreamReader 读取指定文件并指定使用的编码

import java.io.*;
public class InputStreamReaderExample {
    public static void main(String[] args) {
        try {
            // 创建 InputStreamReader 指定编码读取文件
            FileInputStream fileInputStream = new FileInputStream("input.txt"); // 指定文件路径
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); // 指定编码
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // BufferedReader 字符缓冲流读取文件
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
            // 关闭资源
            bufferedReader.close();
            inputStreamReader.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // e.printStackTrace()方法会将异常的堆栈跟踪信息打印到标准错误流(System.err)。堆栈跟踪信息包含了异常发生的位置、方法调用的轨迹以及导致异常的原因等详细信息,有助于开发者定位和解决问题。
    }
}

使用 OutputStreamWriter 写入文件并指定使用的编码

import java.*;
public class OutputStreamWriterExample {
  public static void main(String[] args) {
    // 输出流
    FileOutputSteam fps = new FileOutputSteam("output.txt");
    OutputStreamWriter osw = new OutputStreamWriter(fps, "UTF-8");
    // 写入
    for (int i = 0; i < 10; i++) {
      osw.write("OutputStreamWriterExample\r\n");
      osw.flush();
    }
    // 关闭流
    osw.close();
  }
}

File 类

java.io.FileJava 标准类库中用于表示文件和目录路径的类。它提供了一组方法,可以操作文件和目录,如 创建、删除、重命名、检查文件属性等

API 作用
createNewFile() 创建一个新文件
mkdir() 创建一个新目录
delete() 删除文件或空目录
exists() 判断File对象所代表的对象是否存在
getAbsolutePath() 获取文件的绝对路径
getName() 取得名字
getParent() 获取文件 / 目录所在的目录
isDirectory() 是否是目录
isFile 是否为文件
length() 获得文件的长度
listFiles() 列出目录中的所有内容
renameTo() 修改文件名

获取文件路径分隔符和名称分隔符

import java.io.File;
public class GetSeparator {
  public static void main(String[] args) {
    separator();
  }
  public static void separator() {
    // 获取路径分隔符
    System.out.print("路径分隔符" + File.pathSeparator);
    // 获取名称分隔符
    System.out.print("路径分隔符" + File.separator);
  }
}

文件操作

创建文件

import java.io.File;
public class FileOpe {
  public static void main(String[] args) throw Exception {
    fileOp();
  }
  public static void fileOp() throw Exception {
    File file = new File("D:\\file.txt");
    // System.out.print(file.toString()); // d:\file.txt
    if(file.exists()) {
      boolean b = file.createNewFile();
      System.out.print("创建结果" + b);
    }
  }
}

删除文件

import java.io.File;
public class FileOpe {
  public static void main(String[] args) throw Exception {
    fileOp();
  }
  public static void fileOp() throw Exception {
    File file = new File("D:\\file.txt");
    if(file.exists()) {
      boolean b = file.createNewFile();
      System.out.print("创建结果" + b);
    }
    // 删除文件
    // 1. 直接删除
    // file.delete();
    // 2. jvm退出时删除
    file.deleteOnExit();
    Thread.sleep(5000);
  }
}

获取文件信息

import java.io.File;
public class FileOpe {
  public static void main(String[] args) throw Exception {
    fileOp();
  }
  public static void fileOp() throw Exception {
    File file = new File("D:\\file.txt");
    if(file.exists()) {
      boolean b = file.createNewFile();
      System.out.print("创建结果" + b);
    }
    // 获取文件信息
    System.out.print("文件名称" + file.getName());
    System.out.print("获取父目录" + file.getParent());
    System.out.print("获取长度" + file.length());
    System.out.print("获取文件绝对路径" + file.getAbsolutePath());
    System.out.print("获取路径" + file.getPath());
    System.out.print("获取文件创建时间" + new Date(file.lastModified()).toLocaleString());
  }
}

判断文件信息

import java.io.File;
public class FileOpe {
  public static void main(String[] args) throw Exception {
    fileOp();
  }
  public static void fileOp() throw Exception {
    File file = new File("D:\\file.txt");
    if(file.exists()) {
      boolean b = file.createNewFile();
      System.out.print("创建结果" + b);
    }
    // 判断
    System.out.print("文件是否可写" + file.canWrite());
    System.out.print("是否为文件" + file.isFile());
    System.out.print("文件是否隐藏" + file.isHidden());
  }
}

文件夹操作

创建文件夹

import java.io.File;
public class FileOpe {
  public static void main(String[] args) throw Exception {
    directoryOpe();
  }
  public static void directoryOpe() throw Exception {
    File dir = new File("d:\\aaa\\bbb\\ccc");
    // System.out.print(dir.toString()); // d:\aaa\bbb\ccc
    if (!dir.exists()) {
      // dir.mkdir(); // 只能创建单级目录
      System.out.print("创建状态: " + dir.mkdirs()); // true
    }
  }
}

删除文件夹

import java.io.File;
public class FileOpe {
  public static void main(String[] args) throw Exception {
    directoryOpe();
  }
  public static void directoryOpe() throw Exception {
    File dir = new File("d:\\aaa\\bbb\\ccc");
    // System.out.print(dir.toString()); // d:\aaa\bbb\ccc
    if (!dir.exists()) {
      // dir.mkdir(); // 只能创建单级目录
      System.out.print("创建状态: " + dir.mkdirs()); // true
    }
    // 1. 直接删除
    // System.out.print("删除结果" + dir.delete()); // 注意删除空目录
    // 2. 使用jvm删除
    dir.deleteOnExit();
    Thread.sleep(5000);
  }
}

获取文件夹信息

import java.io.File;
public class FileOpe {
  public static void main(String[] args) throw Exception {
    directoryOpe();
  }
  public static void directoryOpe() throw Exception {
    File dir = new File("d:\\aaa\\bbb\\ccc");
    // System.out.print(dir.toString()); // d:\aaa\bbb\ccc
    if (!dir.exists()) {
      // dir.mkdir(); // 只能创建单级目录
      System.out.print("创建状态: " + dir.mkdirs()); // true
    }
    // 获取文件信息
    System.out.print("文件名称" + dir.getName());
    System.out.print("获取父目录" + dir.getParent());
    System.out.print("获取文件绝对路径" + dir.getAbsolutePath());
    System.out.print("获取路径" + dir.getPath());
    System.out.print("获取文件创建时间" + new Date(dir.lastModified()).toLocaleString());
  }
}

判断文件夹信息

import java.io.File;
public class FileOpe {
  public static void main(String[] args) throw Exception {
    directoryOpe();
  }
  public static void directoryOpe() throw Exception {
    File dir = new File("d:\\aaa\\bbb\\ccc");
    // System.out.print(dir.toString()); // d:\aaa\bbb\ccc
    if (!dir.exists()) {
      // dir.mkdir(); // 只能创建单级目录
      System.out.print("创建状态: " + dir.mkdirs()); // true
    }
    // 判断
    System.out.print("是否为文件夹" + dir.isDirectory());
    System.out.print("文件夹是否隐藏" + dir.isHidden());
  }
}

遍历文件夹内容

import java.io.File;
public class FileOpe {
  public static void main(String[] args) throw Exception {
    directoryOpe();
  }
  public static void directoryOpe() throw Exception {
    File dir = new File("d:\\aaa\\bbb\\ccc");
    // System.out.print(dir.toString()); // d:\aaa\bbb\ccc
    if (!dir.exists()) {
      // dir.mkdir(); // 只能创建单级目录
      System.out.print("创建状态: " + dir.mkdirs()); // true
    }
    // 遍历文件夹
    File dir2 = new File("d:\\图片");
    String[] files = dir2.list();
    for(String item : files ) {
      System.out.println(item);
    }
  }
}

FileFilter 接口

FileFilter 接口 是 Java 标准库中的一个接口,位于 java.io 包下. 它用于筛选文件列表的方法,使得可以选择性地选择需要的文件.

FileFilter 接口 是一个函数式接口,只有一个抽象方法 accept(File pathname),该方法接收一个待测试的文件对象(File类型)作为参数,返回一个布尔值. 如果文件符合条件,返回 true,否则返回 false.

public interface FileFilter 
  - boolean accept(File pathname)
import java.io.File;
import java.io.FileFilter;
public class FileFilterExample {
    public static void main(String[] args) {
        File directory = new File("path/to/directory");
        // 创建一个 FileFilter 匿名内部类来筛选以 ".txt" 结尾的文件
        FileFilter txtFileFilter = new FileFilter() {
            @Override
            public boolean accept(File pathname) {
              // endsWith 字符串方法筛选文件是否以 txt 结尾 
                return pathname.isFile() && pathname.getName().endsWith(".txt");
            }
        };
        // 获取目录下所有满足筛选条件的文件
        File[] txtFiles = directory.listFiles(txtFileFilter);
        // 输出结果
        for (File file : txtFiles) {
            System.out.println(file.getName());
        }
    }
}

递归遍历和递归删除

递归遍历

import java.*;
public class FileDemo {
  public static void main(String[] args) throw Exception {
    FileOpe(new File("d:\\demo"));
  }
  /**
  * @ File dir 接收一个 File 类型参数, 用于递归判断
  */
  public static void FileOpe(File dir) throw Exception {
    File[] files = dir.listFile();
    // 如果数组不为 null 并且 数组不为 []
    if (files != null && files.length > 0) {
      for(File file : files) {
        if (file.isDerectory()) {
          FileOpe(file); // 如果某一项为文件夹,那就对某个文件夹进行递归操作
        } else {
          System.out.print(file.getAbsolutePath());
        }
      }
    }
  }
}

递归删除

找 chatGPT 改了一下,懒得手敲了

import java.io.*;
public class FileDemo {
    public static void main(String[] args) throws Exception {
        FileOpe(new File("d:\\demo"));
    }
    /**
     * @param dir 接收一个 File 类型参数,用于递归判断
     */
    public static void FileOpe(File dir) throws Exception {
        File[] files = dir.listFiles();
        // 如果数组不为 null 并且数组不为空
        if (files != null && files.length > 0) {
            for (File file : files) {
                if (file.isDirectory()) {
                    FileOpe(file); // 如果某一项为文件夹,那就对该文件夹进行递归操作
                } else {
                    System.out.println(file.getAbsolutePath());
                    file.delete(); // 删除文件
                }
            }
        }
        dir.delete(); // 删除文件夹
    }
}

Properties

JavaProperties 是一种用于管理配置信息的类

它继承自 Hashtable 类,因此它具有 Hashtable 的所有特性和方法

Properties 类以键值对的形式存储配置数据,其中键和值都是字符串类型

遍历Properties集合

import java.*;
public class PropertiesDemo {
  public static void main(String[] args) {
    // 创建 Properties
    Proerties p = new Properties();
    // 添加key value 
    p.setProperty("name", "Jerry");
    p.setProperty("age", "3");
    // 遍历
    Set<String> propNames = p.stringPropertyNames();
    for(String pro : propNames) {
      System.out.println(pro + " === " + p.getProperty(pro));
    }
    // 和流有关的方法
    PrintWriter pw = new PrintWriter("d:\\a.txt");
    p.list(pw);
    pw.close();
    // store 方法
    // store() 是 Properties 类的一个方法,用于将属性列表存储到输出流中
    // 第一个参数是输出流对象,可以是 FileOutputStream、BufferedOutputStream 等
    // 第二个参数是一个字符串,表示对存储的属性列表进行注释
    FileOutputStream fos = new FileOutputStream("d:\\a.txt");
    p.store(fos, "注释");
    fos.close();
    // load 方法加载
    Properties p2 = new Properties();
    FileInputStream fis = new FileInputStream("d:\\config.properties");
    p2.load(fis);
    fis.close();
    System.out.println(p2.toString());
  }
}

完结傻花

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

相关文章
|
16天前
|
Java 调度
Java中常见锁的分类及概念分析
Java中常见锁的分类及概念分析
16 0
|
2天前
|
Java API
Java基础&API(3)
Java基础&API(3)
|
2天前
|
Java 机器人 API
Java基础&常用API(1)
Java基础&常用API(1)
|
3天前
|
安全 Java 程序员
|
3天前
|
Java API
Java从入门到精通:2.1.5深入学习Java核心技术之文件操作
Java从入门到精通:2.1.5深入学习Java核心技术之文件操作
|
7天前
|
Java API Apache
ZooKeeper【基础 03】Java 客户端 Apache Curator 基础 API 使用举例(含源代码)
【4月更文挑战第11天】ZooKeeper【基础 03】Java 客户端 Apache Curator 基础 API 使用举例(含源代码)
24 11
|
8天前
|
安全 Java API
java借助代理ip,解决访问api频繁导致ip被禁的问题
java借助代理ip,解决访问api频繁导致ip被禁的问题
|
11天前
|
存储 安全 Java
说说Java 8 引入的Stream API
说说Java 8 引入的Stream API
12 0
|
11天前
|
分布式计算 Java API
Java 8新特性之Lambda表达式与Stream API
【4月更文挑战第16天】本文将介绍Java 8中的两个重要新特性:Lambda表达式和Stream API。Lambda表达式是Java 8中引入的一种新的编程语法,它允许我们将函数作为参数传递给其他方法,从而使代码更加简洁、易读。Stream API是Java 8中引入的一种新的数据处理方式,它允许我们以声明式的方式处理数据,从而使代码更加简洁、高效。本文将通过实例代码详细讲解这两个新特性的使用方法和优势。
|
12天前
|
安全 Java API
RESTful API设计与实现:Java后台开发指南
【4月更文挑战第15天】本文介绍了如何使用Java开发RESTful API,重点是Spring Boot框架和Spring MVC。遵循无状态、统一接口、资源标识和JSON数据格式的设计原则,通过创建控制器处理HTTP请求,如示例中的用户管理操作。此外,文章还提及数据绑定、验证、异常处理和跨域支持。最后,提出了版本控制、安全性、文档测试以及限流和缓存的最佳实践,以确保API的稳定、安全和高效。