JAVA文件IO--3

文件系统操作 ==》File

文件内容操作 ==》流对象 Stream

流对象 --》通过一系列类表示

1.字节流 InputStream FileInputStream 以字节为单位

OutputStream FileOutputStream

2.字符流 Reader FileReader 以字符为单位(字符集)

Writer FileWriter

打开文件(构造对象)

读文件/写文件(Read/Writer) 读系列 输出型参数

关闭文件 文件描述符表(进程PCB中的属性)--》文件资源泄露 close try with resources

例1

扫描指定目录,并找到名称中包含指定字符的所有普通文件(不包含目录),并且后续访问用户是否要删除该文件

思路

只扫描指定目录

list/listFiles ==》遍历文件名 ==》判定是否包含指定字符串 ==》本质上是N叉树

如果要扫描子目录 递归 二叉树

列出当前目录中包含的所有文件/目录

循环遍历

判断当前文件是普通文件还是目录

如果普通文件

判断文件名是否包含指定字符串

删除

如果是目录

从当前目录,递归执行该操作

代码思路

1.让用户通过控制台输入路径和指定字符串

2.需要对用户的输入进行校验

3.单独创建方法,完成递归查找操作

代码
java 复制代码
package io;

import java.io.File;
import java.util.Scanner;

public class Demo12 {
    public static void main(String[] args) {
        // 1. 让用户通过控制台输入路径和指定字符串
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的路径:");
        String basePath = scanner.next();
        System.out.println("请输入要搜索的字符串:");
        String word = scanner.next();

        // 2. 需要对用户的输入进行校验
        // 看一下 basePath 是否是合法的路径.
        File baseFile = new File(basePath);
        if (!baseFile.exists() || !baseFile.isDirectory()) {
            System.out.println("输入的路径有误!");
            return;
        }
        if (word.isEmpty()) {
            System.out.println("输入的搜索字符串不能为空");
            return;
        }

        // 3. 单独创建方法, 完成递归查找操作
        scanDir(baseFile, word);
    }

    private static void scanDir(File baseFile, String word) {
        // 1. 列出 baseFile 下的所有文件
        //    希望直接拿到 File 对象. (判定文件是普通文件还是目录)
        File[] files = baseFile.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        // 2. 遍历数组
        for (File f : files) {
            System.out.println("当前搜索文件: " + f.getAbsolutePath());
            if (f.isFile()) {
                // 针对文件名做判定
                dealFile(f, word);
            } else if (f.isDirectory()) {
                // 进行递归操作了.
                scanDir(f, word);
            }
        }
    }

    private static void dealFile(File f, String word) {
        if (f.getName().contains(word)) {
            // 提示用户, 是否要进行删除
            System.out.println("是否删除 " + f.getAbsolutePath() + " ? (Y/n)");
            Scanner scanner = new Scanner(System.in);
            String choice = scanner.next();
            if (choice.equals("Y") || choice.equals("y")) {
                f.delete();
            } else {
                // 用户输入 N 或者输入其他任何内容, 都不触发删除.
            }
        }
    }
}

例2

进行普通文件的复制

思路与拓展

File类 rename to ==》移动文件

复制文件 --》1.打开要复制的源文件

2.创建要复制的目标文件

3.把源文件的每个字节,读取出来,写入目标文件

源文件 -- 必须存在

目标文件 -- 可以不存在(创建),但目标路径必须存在(getParent)

一般,文本文件 -- 字符流

二进制文件 -- 字节流

复制文件,需要逐个字节拷贝,如果文件较大,消耗时间 ==》O(N)

移动文件,计算改名字,比较快 ==》O(1)

代码思路

1.先让用户输入要复制的文件路径(源文件,目标文件)

2.对2个路径进行判断

源文件--是否存在

目标文件--目标文件所在目录是否存在

目标文件是否存在,若不存在则创建

代码
java 复制代码
package io;

import java.io.*;
import java.util.Scanner;


public class Demo14 {
    public static void main(String[] args) {
        // 1. 输入要扫描的路径, 以及要搜索的关键词
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的路径:");
        String basePath = scanner.next();
        System.out.println("请输入要搜索的关键词:");
        String word = scanner.next();

        // 2. 对输入内容进行校验
        File baseFile = new File(basePath);
        if (!baseFile.exists() || !baseFile.isDirectory()) {
            System.out.println("输入的路径不存在");
            return;
        }
        if (word.isEmpty()) {
            System.out.println("输入的搜索字符串不能为空");
            return;
        }

        // 3. 递归的进行搜索了.
        scanDir(baseFile, word);
    }

    private static void scanDir(File baseFile, String word) {
        File[] files = baseFile.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File file : files) {
            System.out.println("当前搜索到文件: " + file.getAbsolutePath());
            if (file.isFile()) {
                dealFile(file, word);
            } else if (file.isDirectory()) {
                scanDir(file, word);
            }
        }
    }

    private static void dealFile(File file, String word) {
        // 先判定文件名是否包含
        if (file.getName().contains(word)) {
            System.out.println("找到文件名匹配的结果: " + file.getAbsolutePath());
            return;
        }
        // 判定文件内容是否包含.
        StringBuilder content = new StringBuilder();
        try (Reader reader = new FileReader(file)) {
            while (true) {
                char[] chars = new char[1024];
                int n = reader.read(chars);
                if (n == -1) {
                    break;
                }
                content.append(chars, 0, n);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 判定文件内容是否包含 word
        if (content.indexOf(word) != -1) {
            System.out.println("找到文件内容匹配的结果: " + file.getAbsolutePath());
        }
    }
}

例3

扫描指定目录,并找到名称或者内容中包含指定字符的所有普通文件(不包含目录)

代码思路

1.输入要扫描的路径,以及要搜索的关键词

2.对输入内容进行校验

3.递归搜索

代码
java 复制代码
package io;

import java.io.*;
import java.util.Scanner;


public class Demo14 {
    public static void main(String[] args) {
        // 1. 输入要扫描的路径, 以及要搜索的关键词
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的路径:");
        String basePath = scanner.next();
        System.out.println("请输入要搜索的关键词:");
        String word = scanner.next();

        // 2. 对输入内容进行校验
        File baseFile = new File(basePath);
        if (!baseFile.exists() || !baseFile.isDirectory()) {
            System.out.println("输入的路径不存在");
            return;
        }
        if (word.isEmpty()) {
            System.out.println("输入的搜索字符串不能为空");
            return;
        }

        // 3. 递归的进行搜索了.
        scanDir(baseFile, word);
    }

    private static void scanDir(File baseFile, String word) {
        File[] files = baseFile.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File file : files) {
            System.out.println("当前搜索到文件: " + file.getAbsolutePath());
            if (file.isFile()) {
                dealFile(file, word);
            } else if (file.isDirectory()) {
                scanDir(file, word);
            }
        }
    }

    private static void dealFile(File file, String word) {
        // 先判定文件名是否包含
        if (file.getName().contains(word)) {
            System.out.println("找到文件名匹配的结果: " + file.getAbsolutePath());
            return;
        }
        // 判定文件内容是否包含.
        StringBuilder content = new StringBuilder();
        try (Reader reader = new FileReader(file)) {
            while (true) {
                char[] chars = new char[1024];
                int n = reader.read(chars);
                if (n == -1) {
                    break;
                }
                content.append(chars, 0, n);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 判定文件内容是否包含 word
        if (content.indexOf(word) != -1) {
            System.out.println("找到文件内容匹配的结果: " + file.getAbsolutePath());
        }
    }
}
相关推荐
2501_944525548 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 预算详情页面
android·开发语言·前端·javascript·flutter·ecmascript
heartbeat..8 小时前
Redis 中的锁:核心实现、类型与最佳实践
java·数据库·redis·缓存·并发
8 小时前
java关于内部类
java·开发语言
好好沉淀8 小时前
Java 项目中的 .idea 与 target 文件夹
java·开发语言·intellij-idea
gusijin8 小时前
解决idea启动报错java: OutOfMemoryError: insufficient memory
java·ide·intellij-idea
To Be Clean Coder8 小时前
【Spring源码】createBean如何寻找构造器(二)——单参数构造器的场景
java·后端·spring
lsx2024068 小时前
FastAPI 交互式 API 文档
开发语言
吨~吨~吨~8 小时前
解决 IntelliJ IDEA 运行时“命令行过长”问题:使用 JAR
java·ide·intellij-idea
你才是臭弟弟8 小时前
SpringBoot 集成MinIo(根据上传文件.后缀自动归类)
java·spring boot·后端
短剑重铸之日8 小时前
《设计模式》第二篇:单例模式
java·单例模式·设计模式·懒汉式·恶汉式