java文件

news2024/10/2 16:18:38

一.File类

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

我的代码:

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

public class Test1 {
    private static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) throws IOException {
        System.out.println("请输入目标目录:");
        File rootPath = new File(scanner.next());
        if (!rootPath.isDirectory()) {
            System.out.println("目标目录错误");
            return;
        }
        System.out.println("请输入关键字");
        String word = scanner.next();

        fingDir(rootPath, word);
    }

    private static void fingDir(File rootPath, String word) throws IOException {
        File[] files = rootPath.listFiles();

        if (files == null || files.length == 0) {
            return;
        }

        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i].getCanonicalPath());
            if (files[i].isFile()) {
                delFile(files[i], word);
            } else {
                fingDir(files[i], word);
            }
        }
    }

    private static void delFile(File file, String word) {
        if (file.getName().contains(word)) {
            System.out.println("找到了,是否删除y/n");
            if (scanner.next().equals("y")) {
                file.delete();
            }
        }
    }
}

答案代码:

 

/**
 * 扫描指定目录,并找到名称中包含指定字符的所有普通文件(不包含目录),并且后续询问用户是否要删除该文件
 *
 * @Author 比特就业课
 * @Date 2022-06-29
 */
public class file_2445 {
    public static void main(String[] args) {
        // 接收用户输入的路径
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的目录:");
        String rootPath = scanner.next();
        if (rootPath == null || rootPath.equals("")) {
            System.out.println("目录不能为空。");
            return;
        }
        // 根据目录创建File对象
        File rootDir = new File(rootPath);
        if (rootDir.isDirectory() == false) {
            System.out.println("输入的不是一个目录,请检查!");
            return;
        }

        // 接收查找条件
        System.out.println("请输入要找出文件名中含的字符串:");
        String token = scanner.next();
        // 用于存储符合条件的文件
        List<File> fileList = new ArrayList<>();
        // 开始查找
        scanDir(rootDir, token, fileList);
        // 处理查找结果
        if (fileList.size() == 0) {
            System.out.println("没有找到符合条件的文件。");
            return;
        }
        for (File file : fileList) {
            System.out.println("请问您要删除文件" + file.getAbsolutePath() + "吗?(y/n)");
            String order = scanner.next();
            if (order.equals("y")) {
                file.delete();
            }
        }
    }

    private static void scanDir(File rootDir, String token, List<File> fileList) {
        File[] files = rootDir.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        // 开始查找
        for (File file:files) {
            if (file.isDirectory()) {
                // 如果是一个目录就递归查找子目录
                scanDir(file, token, fileList);
            } else {
                // 如果是符合条件的文件就记录
                System.out.println(token);
                if (file.getName().contains(token)) {
                    fileList.add(file.getAbsoluteFile());
                }
            }
        }
    }
}

三.进行普通文件的复制

我的代码:

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

public class Test2 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入目标文件的路径");
        File file1 = new File(scanner.next());
        if (!file1.isFile()) {
            System.out.println("目标文件错误");
            return;
        }
        System.out.println("请输入新文件的路径");
        File file2 = new File(scanner.next());
        if (!file2.getParentFile().isDirectory()) {
            System.out.println("新文件路径错误");
            return;
        }

        copyFile(file1, file2);
    }

    private static void copyFile(File file1, File file2) throws IOException {
        try(InputStream inputStream = new FileInputStream(file1);OutputStream outputStream = new FileOutputStream(file2)) {
            while (true) {
                byte[] buffer = new byte[2048];
                int n = inputStream.read(buffer);
                System.out.println(n);
                if (n == -1) {
                    System.out.println("结束");
                    break;
                } else {
                    outputStream.write(buffer, 0, n);
                }
            }
        }
    }
}
/**
 * 进行普通文件的复制
 * 
 * @Author 比特就业课
 * @Date 2022-06-29
 */
public class File_2446 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 接收源文件目录
        System.out.println("请输入源文件的路径:");
        String sourcePath = scanner.next();
        if (sourcePath == null || sourcePath.equals("")) {
            System.out.println("源文路径不能为空。");
            return;
        }
        // 实例源文件
        File sourceFile = new File(sourcePath);
        // 校验合法性
        // 源文件不存在
        if (!sourceFile.exists()) {
            System.out.println("输入的源文件不存在,请检查。");
            return;
        }
        // 源路径对应的是一个目录
        if (sourceFile.isDirectory()) {
            System.out.println("输入的源文件是一个目录,请检查。");
            return;
        }

        // 输入目标路径
        System.out.println("请输入目标路径:");
        String destPath = scanner.next();
        if (destPath == null || destPath.equals("")) {
            System.out.println("目标路径不能为空。");
            return;
        }
        File destFile = new File(destPath);
        // 检查目标路径合法性
        // 已存在
        if (destFile.exists()) {
            // 是一个目录
            if (destFile.isDirectory()) {
                System.out.println("输入的目标路径是一个目录,请检查。");
            }
            // 是一个文件
            if (destFile.isFile()) {
                System.out.println("文件已存在,是否覆盖,y/n?");
                String input = scanner.next();
                if (input != null && input.toLowerCase().equals("")) {
                    System.out.println("停止复制。");
                    return;
                }
            }
        }

        // 复制过程

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // 1. 读取源文件
            inputStream = new FileInputStream(sourceFile);
            // 2. 输出流
            outputStream = new FileOutputStream(destFile);
            // 定义一个缓冲区
            byte[] byes = new byte[1024];
            int length;
            while (true) {
                // 获取读取到的长度
                length = inputStream.read(byes);
                // 值为-1表示没有数据读出
                if (length == -1) {
                    break;
                }
                // 把读到的length个字节写入到输出流
                outputStream.write(byes, 0, length);
            }
            // 将输出流中的数据写入文件
            outputStream.flush();
            System.out.println("复制成功。" + destFile.getAbsolutePath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭输入流
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 关闭输出流
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

答案代码: 

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

我的代码:

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

public class Test3 {

    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        System.out.println("请输入路径");
        File rootDir = new File(scanner.next());
        if (!rootDir.isDirectory()) {
            System.out.println("目录输入错误");
            return;
        }
        System.out.println("请输入名称");
        String word = scanner.next();

        findFile(rootDir, word);
    }

    private static void findFile(File rootDir, String word) throws IOException {
        File[] files = rootDir.listFiles();

        if (files == null || files.length == 0) {
            return;
        }

        for (File f : files) {
            if (f.isFile()) {
                isFind(f, word);
            } else {
                findFile(f, word);
            }
        }
    }

    private static void isFind(File f, String word) throws IOException {
        if (f.getName().contains(word)) {
            System.out.println("找到了" + f.getPath());
        } else {
            try (Reader reader = new FileReader(f)) {
                Scanner scanner1 = new Scanner(reader);
                String in = scanner1.nextLine();
                if (in.contains(word)) {
                    System.out.println("找到了" + f.getPath());
                } else {
                    return;
                }
            }
        }
    }
}

答案代码: 

 

/**
 * 扫描指定目录,并找到名称或者内容中包含指定字符的所有普通文件(不包含目录)
 *
 * @Author 比特就业课
 * @Date 2022-06-28
 */
public class File_2447 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        // 接收用户输入的路径
        System.out.println("请输入要扫描的路径:");
        String rootPath = scanner.next();
        // 校验路径合法性
        if (rootPath == null || rootPath.equals("")) {
            System.out.println("路径不能为空。");
            return;
        }
        // 根据输入的路径实例化文件对象
        File rootDir = new File(rootPath);
        if (rootDir.exists() == false) {
            System.out.println("指定的目录不存在,请检查。");
            return;
        }
        if (rootDir.isDirectory() == false) {
            System.out.println("指定的路径不是一个目录。请检查。");
            return;
        }

        // 接收要查找的关键字
        System.out.println("请输入要查找的关键字:");
        String token = scanner.next();
        if (token == null || token.equals("")) {
            System.out.println("查找的关键字不能为空,请检查。");
            return;
        }

        // 遍历目录查找符合条件的文件
        // 保存找到的文件
        List<File> fileList = new ArrayList<>();
        scanDir(rootDir, token, fileList);

        // 打印结果
        if (fileList.size() > 0) {
            System.out.println("共找到了 " + fileList.size() + "个文件:");
            for (File file: fileList) {
                System.out.println(file.getAbsoluteFile());
            }
        } else {
            System.out.println("没有找到相应的文件。");
        }

    }

    private static void scanDir(File rootDir, String token, List<File> fileList) throws IOException {
        // 获取目录下的所有文件
        File[] files = rootDir.listFiles();
        if (files == null || files.length == 0) {
            return;
        }

        // 遍历
        for (File file : files) {
            if (file.isDirectory()) {
                // 如果是文件就递归
                scanDir(file, token, fileList);
            } else {
                // 文件名是否包含
                if (file.getName().contains(token)) {
                    fileList.add(file);
                } else {
                    if (isContainContent(file, token)) {
                        fileList.add(file.getAbsoluteFile());
                    }
                }

            }
        }
    }

    private static boolean isContainContent(File file, String token) throws IOException {
        // 定义一个StringBuffer存储读取到的内容
        StringBuffer sb = new StringBuffer();
        // 输入流
        try (InputStream inputStream = new FileInputStream(file)) {
            try (Scanner scanner = new Scanner(inputStream, "UTF-8")) {
                // 读取每一行
                while (scanner.hasNext()) {
                    // 一次读一行
                    sb.append(scanner.nextLine());
                    // 加入一行的结束符
                    sb.append("\r\n");
                }
            }
        }
        return sb.indexOf(token) != -1;
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/865039.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

对于msvcr120.dll丢失的问题,分享几种解决方法

msvcr120.dll的作用是提供一系列的运行时函数和功能&#xff0c;以便应用程序能够正常运行。这些函数和功能包括内存管理、异常处理、输入输出操作、数学运算等。在没有这个库文件的情况下&#xff0c;应用程序可能无法正常启动或执行特定的功能&#xff0c;甚至会出现错误提示…

Spring MVC【一篇搞定】

Spring MVC 文章目录 Spring MVC一、什么是 Spring MVC二、介绍MVC2.1、Spring MVC 和 MVC 之间的关系 三、创建 Spring MVC四、掌握 Spring MVC 的核心 ☆☆☆☆4.1、Spring 热部署4.2、实现用户与程序的连接 ☆4.2.1、RequestMapping4.2.2、GetMapping/PostMapping 4.3、获取…

《Zookeeper》源码分析(七)之 NIOServerCnxn的工作原理

目录 NIOServerCnxnreadPayload()handleWrite(k)process() NIOServerCnxn 在上一节IOWorkRequest的doWork()方法中提到会将IO就绪的key通过handleIO()方法提交给NIOServerCnxn处理&#xff0c;一个NIOServerCnxn代表客户端与服务端的一个连接&#xff0c;它用于处理两者之间的…

JavaScript 中 let 和 var 的区别

首先&#xff0c;let 和 var 都是用于声明变量的关键字&#xff0c;在老版 JavaScript 中也许你会见到 var 方式来声明变量&#xff0c;而现如今几乎都是使用 let 进行声明&#xff0c;接下来看看这两个关键字之间的区别。 1、作用域 var var 声明的变量在函数内部有效&#x…

【什么是应变波齿轮又名谐波驱动?机器人应用的完美齿轮组!?】

什么是应变波齿轮又名谐波驱动&#xff1f;机器人应用的完美齿轮组&#xff01;&#xff1f; 1. 什么是应变波齿轮&#xff1f;2. 工作原理3. 应变波齿轮 – 谐波驱动 3D 模型4. 3D 打印应变波齿轮 – 谐波驱动5. 总结 在本教程中&#xff0c;我们将学习什么是应变波齿轮&#…

关于使用 heatmap.js创建热力图并应用在cesuim上的坐标定位问题

废话少说&#xff0c;heatmap.js的用法我不在赘述&#xff0c;此文主要解决其热力点坐标定位在cesuim上的问题。 热力图容器 我们知道&#xff0c;热力图需要用有一个容器节点来存放它生成的图片&#xff1a;<div class"div-heatMap"></div> 而其中容器…

【ElasticSearch入门】

目录 1.ElasticSearch的简介 2.用数据库实现搜素的功能 3.ES的核心概念 3.1 NRT(Near Realtime)近实时 3.2 cluster集群&#xff0c;ES是一个分布式的系统 3.3 Node节点&#xff0c;就是集群中的一台服务器 3.4 index 索引&#xff08;索引库&#xff09; 3.5 type类型 3.6 doc…

360安全卫士右下角广告弹窗太多怎么彻底关闭?

360安全卫士右下角广告弹窗太多怎么彻底关闭&#xff1f; 1、卸载360安全卫士&#xff0c;选择继续卸载&#xff0c;并点击下一步&#xff1b; 2、选择广告弹窗太多&#xff0c;并点击下一步&#xff1b; 3、然后被告知升级极速版永久去广告&#xff0c;可以点击一键去广告。 …

全网超全,接口自动化测试-动态数据生成/替换数据(实战应用)

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 接口自动化过程中…

拂袖一挥,zipfile秒列zip包内容

使用wxpython列出文件夹中的zip文件及内容 最近在做一个文件管理的小工具,需要列出选择的文件夹下的所有zip压缩文件,并在点击某个zip文件时能够显示其中的内容。为此我使用了wxpython来实现这个功能。 1. 导入需要的模块 首先导入程序需要的模块: import wx import os imp…

【C++面向对象】--- 继承 的奥秘(上篇)

个人主页&#xff1a;平行线也会相交&#x1f4aa; 欢迎 点赞&#x1f44d; 收藏✨ 留言✉ 加关注&#x1f493;本文由 平行线也会相交 原创 收录于专栏【C之路】&#x1f48c; 本专栏旨在记录C的学习路线&#xff0c;望对大家有所帮助&#x1f647;‍ 希望我们一起努力、成长&…

git强推覆盖其他项目分支

git强推分支&#xff0c;覆盖其他分支&#xff1b; 操作&#xff1a; 下载branch-1.3代码&#xff1b; $ git clone gitlabgitlab.zte.net:zte-dba-service/branch.git $ git remote add origin2 gitlabgitlab.zte.net:zte-service/branch.git $ git push origin2 master -f注…

UE 5 GAS 在项目中处理AttributeSet相关

这一篇文章是个人的实战经验记录&#xff0c;如果对基础性的内容不了解的&#xff0c;可以看我前面一篇文章对基础的概念以及内容的讲解。 设置AttributeSet 使用GAS之前&#xff0c;首先需要设置参数集AS&#xff0c;这个是用于同步的一些参数&#xff0c;至于如何设置GAS&a…

腾讯云Linux服务器创建、使用和配置的教程

腾讯云Linux服务器创建&#xff0c;先注册腾讯云账号&#xff0c;购买云服务器配置然后选择Linux镜像操作系统&#xff0c;包括云服务器地域、CVM实例、公网IP等配置&#xff0c;然后远程链接到腾讯云服务器快速配置使用教程&#xff1a; 目录 腾讯云Linux服务器创建 创建Li…

远程控制医疗行业应用解析:如何满足医院合规需求?

远程控制医疗行业应用解析&#xff1a;如何满足医院合规需求&#xff1f; 作为一个起源于IT行业的技术&#xff0c;以远程桌面为基础的远程控制技术目前在医疗领域也已经有了比较广阔的应用前景&#xff0c;尤其是在医疗数字化系统/设备的远程运维场景&#xff0c;已经有了一些…

Spring Profile与PropertyPlaceholderConfigurer实现项目多环境配置切换

最近考虑项目在不同环境下配置的切换&#xff0c;使用profile注解搭配PropertyPlaceholderConfigurer实现对配置文件的切换&#xff0c;简单写了个demo记录下实现。 基本知识介绍 Profile Profile通过对bean进行修饰&#xff0c;来限定spring在bean管理时的初始化情况&#…

K8S调度

K8S调度 一、List-Watch 机制 controller-manager、scheduler、kubelet 通过 List-Watch 机制监听 apiserver 发出的事件&#xff0c;apiserver 通过 List-Watch 机制监听 etcd 发出的事件1.scheduler 的调度策略 预选策略/预算策略&#xff1a;通过调度算法过滤掉不满足条件…

CH344Q/L USB转四串口芯片资料下载(合集)

1、产品手册 CH344DS1.PDF - 南京沁恒微电子股份有限公司CH344技术手册&#xff0c;USB转4串口芯片&#xff0c;支持最高6M波特率与硬件流控&#xff0c;支持USB配置功能&#xff0c;提供RS485方向控制与GPIO等信号引脚&#xff0c;可实现PC等平台扩展多串口或多个串口设备升级…

多维时序 | MATLAB实现ZOA-CNN-BiGRU-Attention多变量时间序列预测

多维时序 | MATLAB实现ZOA-CNN-BiGRU-Attention多变量时间序列预测 目录 多维时序 | MATLAB实现ZOA-CNN-BiGRU-Attention多变量时间序列预测预测效果基本介绍模型描述程序设计参考资料 预测效果 基本介绍 1.Matlab基于ZOA-CNN-BiGRU-Attention斑马优化卷积双向门控循环单元网络…

ARTS 挑战打卡的第7天 --- Ubuntu中的WindTerm如何设置成中文,并且关闭shell中Tab键声音(Tips)

前言 &#xff08;1&#xff09;Windterm是一个非常优秀的终端神器。关于他的下载我就不多说了&#xff0c;网上很多。今天我就分享一个国内目前没有找到的这方面的资料——Ubuntu中的WindTerm如何设置成中文&#xff0c;并且关闭shell中Tab键声音。 将WindTerm设置成中文 &…