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());
        }
    }
}
相关推荐
SimonKing1 分钟前
实用,DynamicTP进阶之数据采集与告警
java·后端·程序员
清水白石0083 分钟前
从打印对象到高质量调试:彻底理解 Python 中 `__repr__` 和 `__str__` 的区别
开发语言·python
用户298698530145 分钟前
Java 进阶:基于模板生成 Word 文档的实践思路
java·后端
涛声依旧-底层原理研究所7 分钟前
响应式编程:map与flatMap实战解析
java
枕星而眠8 分钟前
C++ 面向对象核心机制深度解析:多态性、虚函数、虚继承与 final 类
运维·开发语言·c++·后端
Evand J34 分钟前
【MATLAB例程】自适应渐消扩展卡尔曼滤波(AFEKF)三维雷达目标跟踪|效果已调优,附下载链接和运行结果,代码直接运行即可
开发语言·算法·matlab·目标跟踪·卡尔曼滤波·自适应滤波·代码定制
爱装代码的小瓶子35 分钟前
3. 设计buffer模块
linux·服务器·开发语言·c++·php
郝学胜-神的一滴36 分钟前
Qt 高级开发 027: QTabWidget自定义样式表美化实战
开发语言·c++·qt·程序人生·软件构建·用户界面
keykey6.36 分钟前
迁移学习实战:用预训练模型做图像分类
开发语言·人工智能·深度学习·机器学习
双河子思37 分钟前
《代码整洁之道》——读书笔记(持续更新)
开发语言·c++·c#