【Java EE 初阶】文件操作

news2025/4/17 19:41:02

目录

1.什么是文件?

1.在cmd中查看指定目录的树形结构语法

2.文件路径

从当前目录开始找到目标程序(一个点)

返回到上一级目录,再找目标程序(两个点)

2.Java中文件操作

1.File概述

1.属性

2. 构造方法

3.常用方法

 代码展示:

4.常用方法2

3. 文件内容的读写---数据流

1.InputStream概述

2. FileInputStream

构造方法:

 1.输入数据到文件

3.字符流的输出流

4.Scanner类

5.printWrite类

 4.练习扫描文件并删除

1.步骤

2.代码:

3.结果

 4.进行普通文件的复制

1.步骤

2.代码:

3.结果: 


 

 

1.什么是文件?

狭义上的文件:硬盘上保存的数据,都是“文件”来组织的,本质上都是二进制或是字符组织的数组,被打包成一个文件存在硬盘上。常见的文件有图片(png),文本(txt),可执行文件(exe)等

80d0acdabee44141a65d054a87df0b17.png

 

广义上的文件操作系统的主要功能就是对计算机资源进行统一管理与分配。对于Linux来说,所有的计算设备都会被描述(抽象)成文件。(例如:网卡,键盘,打印机)等

451af9d83f6745d09dd72f6a6343714c.png 

树形结构组织随着文件越来越多,如何进行文件的组织呢?就是按照层级结构进行组织---也就是数据结构中的树形结构。而我们平时所谓的文件夹或者目录,就是专门用来存放管理信息的

1.在cmd中查看指定目录的树形结构语法

目录>tree/F

2.文件路径

绝对路径:从根目录开始一直到目标程序的表示方式

相对路径:从当前目录开始,表示目标程序路径的方式

从当前目录开始找到目标程序(一个点)

语法:.+目标程序目录

返回到上一级目录,再找目标程序(两个点)

语法: ..+目标程序目录

 

2.Java中文件操作

92bc6807cc874e018ea621109bd0d7ba.png

输入输出是以内存为参照物的,输入指的是从外部输入到内存,输出指的是把内存中的数据输出到外部(磁盘,网卡等)

1.File概述

1.属性

ebd1e5329f2a4d7086ae193be6da1a3a.png

2. 构造方法

e9838529bd6a49b4b8ad2302874ea02e.png

一般常用第二种 

        File file = new File("D:\\temp");
        File file1 = new File("D:/temp");

反斜杠需要进行转义

3.常用方法

cb60620cd1a545958ef1944257a96c16.png

 代码展示:

public static void main(String[] args) throws IOException {
        File file = new File("D:\\temp\\test\\test.txt");
        //获取父目录
        System.out.println(file.getParent());
        //获取文件名
        System.out.println(file.getName());
        //获取路径
        System.out.println(file.getPath());
        //获取绝对路径
        System.out.println(file.getAbsoluteFile());
        //获取一个标准路径
        System.out.println(file.getCanonicalFile());
        // 是否存在
        System.out.println(file.exists());
        // 是不是一个目录
        System.out.println(file.isDirectory());
        // 是不是一个文件
        System.out.println(file.isFile());

    }

5e8ad8dd0c2341ecb10b92b054accdbc.png

 平常我们使用标准路径获得的路径比较整洁

4.常用方法2

e993ec677be74d6d982d606e3d219699.png

1.创建一个文件

    public static void main(String[] args) throws IOException {
        File file = new File("D:\\temp\\test\\hello.txt");
        boolean res = file.createNewFile();
        if (res) {
            System.out.println("创建成功!");
        } else {
            System.out.println("创建失败");
        }
    }

97bc0cd2daa04b89a65878176b066347.png

 2.删除一个文件

    public static void main(String[] args) throws IOException {
        File file = new File("D:\\temp\\test\\hello.txt");
        boolean res = file.delete();

        if (res) {
            System.out.println("删除成功!");
        } else {
            System.out.println("删除失败");
        }
    }

48720631d4754711b314c132ed47ba1f.png

3返回file对象代表的目录下的所有文件,以file对象表示

    public static void main(String[] args) {
        File file = new File("D:\\temp\\test");

        //获取目录下的文件和子目录
        String[] list = file.list();
        System.out.println(Arrays.toString(list));

        //获取目录下的文件对象数组
        File[] files = file.listFiles();
        System.out.println(Arrays.toString(files));
    }

 3328b70f8d694d51b7f5e49961ae5cc3.png

4.创建单个目录

    public static void main(String[] args) {
        File file = new File("D:\\temp\\test01");

        //创建单个目录
        boolean res = file.mkdir();
        if (res) {
            System.out.println("创建成功!");
        } else {
            System.out.println("创建失败");
        }
    }

640094469585454b8193626772984db3.png 

 5.创建一连串目录

    public static void main(String[] args) {
        File file = new File("D:/temp/test01/a/b/c");

        //创建单个目录
        boolean res = file.mkdirs();
        if (res) {
            System.out.println("创建成功!");
        } else {
            System.out.println("创建失败");
        }
    }

b183e513915a490d9a6827c05921882f.png

 6.修改文件名称

    public static void main(String[] args) {
        File file = new File("D:/temp/test/hello.txt");
        File file1 = new File("D:/temp/test/hi.txt");
        //创建单个目录
        boolean res = file.renameTo(file1);
        if (res) {
            System.out.println("修改成功!");
        } else {
            System.out.println("修改失败");
        }
    }

3d1636a62b8246dcbbda2c39bf0f1113.png

 7.查看文件读写状态

    public static void main(String[] args) {
        File file = new File("D:/temp/test/hello.txt");

        System.out.println(file.canRead());
        System.out.println(file.canWrite());
    }

03c2c1e93414436eadd2aa6cc71f2828.png

3. 文件内容的读写---数据流

48c9785ee31845f7b432aec65ed2488d.png

 63ac773fa4c14fd9b0828336112118c1.png

1.InputStream概述

InputStream只是一个抽象类,要使用还需要具体的实现类。从文件中读取,使用FileInputStream

 方法:

4b3773c1d6094099aef04303b5405357.png

c595444027c64d1695ca3edf14603ab9.png

1.读取文件中的数据

    public static void main(String[] args) throws IOException {
        File file = new File("D:/temp/test/hello.txt");
        InputStream inputStream = new FileInputStream(file);
        while (true) {
            int resd = inputStream.read();
            if (resd == -1) {
                break;
            }
            System.out.println(resd);
        }
    }

 67488af6d186483b8103c99946cd634b.png

 2.用数组保存读取出来的数据

    public static void main(String[] args) throws IOException {
        File file = new File("D:/temp/test/hello.txt");
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[1024];
        while (true) {
            int resd = inputStream.read(bytes);
            if (resd == -1) {
                break;
            }
            for (int i = 0; i < resd; i++) {
                System.out.println(bytes[i]);
            }
        }
    }

 470b92310c3e4a7a8eeebb63f8a257e0.png

2. FileInputStream

构造方法:

ef2775f31af7470a922f9564aa68059e.png

 1.输入数据到文件

调用write方法就表示通过输出流,把内容写到指定的文件中

文件内容一般先写到缓冲区,缓冲区什么时候将内容写入文件,取决于操作系统

强制写入文件,调用 flash()方法,确保文件内容被立即写入

    public static void main(String[] args) throws IOException {
        File file = new File("D:/temp/test/hello.txt");
        //创建一个输出流
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write('a');
        outputStream.write('b');
        outputStream.write('c');
        //刷新缓存区
        outputStream.flush();
        //关闭输出流
        outputStream.close();

    }

db8ed591636f485681dcf0e0776406f6.png

5f146208fa2b4fbba9f72a9332eaccc3.png

用输出流的方式去写文件,会把之前的文件内容清空

2.读取字符

    public static void main(String[] args) throws IOException {
        File file = new File("D:/temp/test/hello.txt");
        //根据file对象创建一个Reader面向字符的输入流
        FileReader fileReader = new FileReader(file);
        while (true) {
            int res = fileReader.read();
            if (res == -1) {
                break;
            }
            //打印
            System.out.println(res);
        }
        //关闭输出流
        fileReader.close();

    }

3.字符流的输出流

    public static void main(String[] args) throws IOException {
        File file = new File("D:/temp/test/hello.txt");
        //根据file对象创建一个Reader面向字符的输入流
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write("你好");
        fileWriter.write("小锦鲤");
        //刷新
        fileWriter.flush();
        //关闭输出流
        fileWriter.close();

    }

 换行需要自己写转义字符\n进行换行

用输出流的方式去写文件,会把之前的文件内容清空

f04b8fecc6204e1bbeb57f2ffd67ecc8.png

6a3b7277b411475cb6d01adcb8712cef.png

4.Scanner类

    public static void main(String[] args) throws IOException {
        //根据file对象创建一个Reader面向字符的输入流
        FileInputStream inputStream = new FileInputStream("D:/temp/test/hello.txt");
        Scanner sc = new Scanner(inputStream,"UTF-8");
        while (sc.hasNext()) {
            String  s = sc.nextLine();
            System.out.println(s);
        }

    }

5.printWrite类

    public static void main(String[] args) throws IOException {
        //根据file对象创建一个Reader面向字符的输入流
        FileOutputStream outputStream = new FileOutputStream("D:/temp/test/hello.txt");
        PrintWriter printWriter = new PrintWriter(outputStream);
        printWriter.println("小锦鲤");
        printWriter.println("hello");
        printWriter.flush();
        printWriter.close();
    }

7acf3f0645f147e69111f8f2c175233b.png

 4.练习扫描文件并删除

1.步骤

e85b19c2b4ef4245b5bace32406c96d6.png

2.代码:

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

public class deleteFile {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要删除的文件的绝对路径");
        String path = sc.next();
        File file = new File(path);
        //检查是否有效
        //1.检查路径是否存在
        if (!file.exists()) {
            System.out.println("路径不存在哦~");
            return;
        }
        //2.检查是否为有效目录
        if (!file.isDirectory()) {
            System.out.println("不是有效目录哦~");
            return;
        }
        //让用户输入目标字符
        System.out.println("请输入要删除的文件名称");
        String name = sc.next();
        //判断名称是否合法
        //使用 "".equals(name) 避免出现异常
        if (name == null || "".equals(name)) {
            System.out.println("名称不可以为空哦~");
            return;
        }
        //递归进行删除
        delete(file, name);
    }

    public static void delete(File file, String name) throws IOException {
        //获取file下所有文件
        File[] files = file.listFiles();
        //递归终止条件
        if (files == null || files.length == 0) {
            return;
        }
        //遍历数组中的每个文件
        for (int i = 0; i < files.length; i++) {
            //判断是否为文件
            if (files[i].isFile()) {
                //是文件,判断是否为目标文件
                String fileName = files[i].getName();
                if (fileName.contains(name)) {
                    System.out.println("找到文件"+files[i].getCanonicalFile()+"是否确定删除?(Y/N)");
                    //接受用户的选择
                    Scanner sc = new Scanner(System.in);
                    String order = sc.next();
                    //删除(忽视大小写)
                    if ("Y".equalsIgnoreCase(order)) {
                        files[i].delete();
                        System.out.println(files[i].getCanonicalFile()+"删除成功~");
                    }
                }
            } else {
                //是目录则继续递归
                delete(files[i], name);
            }
        }


    }
}

3.结果

 a6a68e9f194d4d2fb319423fd472a082.png

 4.进行普通文件的复制

1.步骤

53a36c69a7d34b4b8644c10a28f061cd.png

2.代码:

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

public class copyFile {
    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("请输入要复制的文件的路径");
        Scanner sc = new Scanner(System.in);
        String sourceName = sc.next();
        //创建文件类实例
        File sourcefile = new File(sourceName);
        //判断文件是否存在
        if (!sourcefile.exists()) {
            System.out.println("文件不存在~");
            return;
        }
        //判断是否是文件
        if (!sourcefile.isFile()) {
            System.out.println("源文件不是一个有效的文件");
            return;
        }
        //接受用户输入的目标文件
        System.out.println("请输入目标文件路径(绝对路径)");
        String destName = sc.next();
        File destFile = new File(destName);
        //判断目标文件路径是否存在
        if (destFile.exists()) {
            System.out.println("目标文件已存在~");
        }
        //判断目标文件的夫目录是否存在
        if (!destFile.getParentFile().exists()) {
            System.out.println("目标文件路径父目录不存在");
        }
        //循环读取源文件到目标路径
        try {
            FileInputStream inputStream = new FileInputStream(sourcefile);
            FileOutputStream outputStream = new FileOutputStream(destFile);
            //定义byte【】的数组用来做输出型参数
            byte[] bytes = new byte[1024];
            while (true) {
                int len = inputStream.read(bytes);
                if (len == -1) {
                    break;
                }
                //写入目标文件
                outputStream.write(bytes);
                //刷新缓存
                outputStream.flush();
            }
            System.out.println("复制成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.结果: 

 02780d5309a34032859949bafbfdfea7.png

2955e3c06a8346a4aeafe64a3dc4acce.png

 

 

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

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

相关文章

CENTO OS上的网络安全工具(二十二)Spark HA swarm容器化集群部署

在Hadoop集群swarm部署的基础上&#xff0c;我们更进一步&#xff0c;把Spark也拉进来。相对来说&#xff0c;在Hadoop搞定的情况下&#xff0c;Spark就简单多了。 一、下载Spark 之所以把这件事还要拿出来讲……当然是因为掉过坑。我安装的时候&#xff0c;hadoop是3.3.5&a…

Unity Metaverse(七)、基于环信IM SDK实现的好友系统、私聊、群聊

文章目录 &#x1f388; 简介&#x1f388; 用户管理&#x1f388; 好友管理&#x1f388; 聊天管理&#x1f538; 发送与接收消息&#x1f538; 消息处理消息项的对象池管理 &#x1f388; 简介 在之前的文章中已经介绍了如何接入环信IM Unity SDK&#xff0c;及基于该SDK实现…

使用Python 构建球体/正方体/多面体/兔子/八面体等点云,Open3D可视化及重建

使用Python 构建球体/正方体/多面体/兔子/八面体等点云&#xff0c;Open3D可视化及重建 点云生成8面体点并拟合绘制表面重建结果。&#xff08;官方示例兔子&#xff0c;8面体&#xff0c;多面体&#xff0c;球体&#xff09; 1. 效果图8面体多面体效果图**俩个整8面体效果图**…

学生宿舍信息管理系统

系列文章 任务6 学生宿舍信息管理系统 文章目录 系列文章一、实践目的与要求1、目的2、要求 二、课题任务三、总体设计1.存储结构及数据类型定义2.程序结构3.所实现的功能函数4、程序流程图 四、小组成员及分工五、 测试宿舍信息录入宿舍信息浏览查询学生所住宿舍楼号、宿舍号…

WPF MaterialDesign 初学项目实战(6):设计首页(2),设置样式触发器

原项目视频 WPF项目实战合集(2022终结版) 26P 源码地址 WPF项目源码 其他内容 WPF MaterialDesign 初学项目实战&#xff08;0&#xff09;:github 项目Demo运行 WPF MaterialDesign 初学项目实战&#xff08;1&#xff09;首页搭建 WPF MaterialDesign 初学项目实战&…

npm、cnpm、yarn、pnpm区别以及pnpm 是凭什么对 npm 和 yarn 降维打击的

安装 1、安装npm需要安装nodejs&#xff0c;node中自带npm包管理器 node下载地址&#xff1a;node.js 2、cnpm安装&#xff08;需要安装npm&#xff09; cnpm是淘宝团队做的npm镜像&#xff0c;淘宝镜像每 10分钟 进行一次同步以保证尽量与官方服务同步。 npm install -g …

secure CRT 自定义主题

文章目录 如何切换 SecureCRT 主题如何新建SecureCRT 主题如何拷贝我的主题,主题名为pic如何设置 SecureCRT 关键字高亮 如何切换 SecureCRT 主题 SecureCRT 自带主题 选择 options -> Edit Default Session -> Terminal -> Emulation -> Terminal xterm optio…

【Linux】-vim的介绍,教你手把手使用vim

&#x1f496;作者&#xff1a;小树苗渴望变成参天大树 ❤️‍&#x1fa79;作者宣言&#xff1a;认真写好每一篇博客 &#x1f4a8;作者gitee:gitee &#x1f49e;作者专栏&#xff1a;C语言,数据结构初阶,Linux,C 如 果 你 喜 欢 作 者 的 文 章 &#xff0c;就 给 作 者 点…

一台电脑同时安装多个tomcat服务器教程,window同时安装tomcat7、tomcat8、tomcat9三个服务器教程

一台电脑同时安装多个tomcat服务器 . 介绍 A. 解释为什么有时需要同时安装多个Tomcat服务器 应用程序隔离&#xff1a;当你需要在同一台设备上运行多个独立的应用程序时&#xff0c;每个应用程序可能需要使用不同的Tomcat配置和环境。通过同时安装多个Tomcat服务器&#xff0…

车载以太网 - SomeIP - 协议用例 - Messages_02

目录 13.1、验证SomeIP-SD中订阅报文Subscribe和SubscribeAck中IPv4 Endpoint Option中ServiceID一样

【JAVA进阶】Stream流

&#x1f4c3;个人主页&#xff1a;个人主页 &#x1f525;系列专栏&#xff1a;JAVASE基础 目录 1.Stream流的概述 2.Stream流的获取 3.Stream流的常用方法 1.Stream流的概述 什么是Stream流&#xff1f; 在Java 8中&#xff0c;得益于Lambda所带来的函数式编程&#xff0…

HNU数据结构与算法分析-作业4-图结构

1. (简答题) 【应用题】11.3 &#xff08;a&#xff09;画出所示图的相邻矩阵表示 &#xff08;b&#xff09;画出所示图的邻接表表示 &#xff08;c&#xff09;如果每一个指针需要4字节&#xff0c;每一项顶点的标号占用2字节&#xff0c;每一条边的权需要2字节&#xff0…

计算机体系结构存储系统

存储系统原理 两种典型的存储系统&#xff1a;Cache存储系统和虚拟存储系统。前者主要目的是提高存储器速度&#xff0c;后者有主存储器和硬盘构成&#xff0c;主要用于扩大存储器容量。 存储系统的访问效率 e T 1 T 1 H ( 1 − H ) T 2 T 1 f ( H , T 2 T 1 ) e\frac{T_…

魔改车钥匙实现远程控车:(4)基于compose和经典蓝牙编写一个控制APP

前言 这篇文章不出意外的话应该是魔改车钥匙系列的最后一篇了&#xff0c;自此我们的魔改计划除了最后的布线和安装外已经全部完成了。 不过由于布线以及安装不属于编程技术范围&#xff0c;且我也是第一次做&#xff0c;就不献丑继续写一篇文章了。 在前面的文章中&#xf…

基于torch实现模型剪枝

一、剪枝分类 所谓模型剪枝&#xff0c;其实是一种从神经网络中移除"不必要"权重或偏差&#xff08;weigths/bias&#xff09;的模型压缩技术。关于什么参数才是“不必要的”&#xff0c;这是一个目前依然在研究的领域。 1.1、非结构化剪枝 非结构化剪枝&#xff08;…

什么是可持续能源?

随着全球经济的不断发展和人口的不断增长&#xff0c;能源问题越来越受到关注。传统能源已经不能满足人们对能源的需求&#xff0c;同时也对环境和健康带来了严重的影响。为了解决这些问题&#xff0c;出现了可持续能源的概念。那么&#xff0c;什么是可持续能源呢&#xff1f;…

逐渐从土里长出来的小花

从土里逐渐长出来的小花&#xff08;这是长出来后的样子&#xff0c;图片压缩了出现了重影~&#xff09; 代码在这里&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>Title</title&g…

MySQL-索引(2)

本文主要讲解MySQL-索引相关的知识点 联合索引前缀索引覆盖索引索引下推索引的优缺点什么时候适合创建索引,什么时候不适合?如何优化索引 ? 索引失效场景 ? 为什么SQL语句使用了索引,却还是慢查询 ? 使用索引有哪些注意事项 ? InnoDB引擎中的索引策略 目录 联合索引 联合…

LeetCode高频算法刷题记录6

文章目录 1. 编辑距离【困难】1.1 题目描述1.2 解题思路1.3 代码实现 2. 寻找两个正序数组的中位数【困难】2.1 题目描述2.2 解题思路2.3 代码实现 3. 合并区间【中等】3.1 题目描述3.2 解题思路3.3 代码实现 4. 爬楼梯【简单】4.1 题目描述4.2 解题思路4.3 代码实现 5. 排序链…

chatgpt赋能Python-python3_9安装numpy

Python 3.9 安装 NumPy 的完整指南 Python是一种功能强大的编程语言&#xff0c;已成为数据分析、人工智能和科学计算领域的主流语言之一。NumPy是一个Python库&#xff0c;用于执行高效的数值计算和科学计算操作。Python 3.9是Python最新版本&#xff0c;带来了许多新功能和改…