• Java中的IO操作


    【前言】Java比较少用于系统软件开发,大部分是业务开发

    掌握基本常识理论(网络(网卡)、文件(硬盘))

    重点是网络——编写实例程序

    一、What

    杂谈

    文件:狭义上,表示硬盘中的数据块

    逻辑上文件由两块数据组成:内容数据+元数据(文件名称,谁啥时候创建在哪儿)

    **文件系统:**操作系统委托文件系统对文件进行组织和管理

    文件系统按照树形组织,进行文件的组织——目录/文件夹也是特殊的文件——文件分为 普通文件+文件夹文件

    文件的位置/路径——定位文件

    反斜杠作分隔符,Java中要转义,所以是两个反斜杠

    绝对路径:从树根开始描述路径(路径存在,并不一定文件一定存在

    相对路径:相对当前所在位置(进程的工作目录),从当前位置出发(有可能先返回上一级,.表示当前位置,返回上一级用… 表示,上上一级 …/…)

    硬盘存储 VS 内存存储

    ​ 硬盘存储:非易失性存储+低速存储(为了弥合速度差,就有了针对硬盘数据读写的各种数据结构和算法;) 更适合块状连续读取——电梯算法

    ​ 因为硬盘的低速性,又有了缓冲区技术,buffer,减少硬盘数据的读写频次,缓冲区是在内存中开辟的一段空间,达到一定条件后(比如应用程序主动要求,比如定时定量冲刷缓冲区)数据统一从缓冲区写回硬盘

    数据

    文本数据

    二进制数据

    二、Java.io.File类——描述文件的管理系统

    获取文件基本信息 + 创建文件 + 删除文件(注意都分为普通文件和目录文件)+ 重命名(实际就是移动文件)

    ListFiels

    1.三个构造方法

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gVvtXjCv-1660788981931)(C:\Users\星\AppData\Roaming\Typora\typora-user-images\1652095846542.png)]

    2.常用方法

    【rename重命名的是路径,相当于移动文件位置】
    在这里插入图片描述

    3.给定起始目录,遍历该目录下的所有文件,ListFiels

    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    /**搜索打印指定名称文件的路径名
     * 以在D:/星/文档目录下打印名为Test.class文件为例
     * @author sunny
     * @date 2022/05/08 15:57
     **/
    public class FingFile {
        static List<String> list = new ArrayList<>();
        public static void main(String[] args) throws IOException {
            File file = new File("D:/星/文档");
            find(file);
            for(String s : list){
                System.out.println(s);
            }
        }
    //			递归遍历    
        public static void find(File dire) throws IOException {
            File[] files = dire.listFiles();
            if(files == null){
                return;
            }
            for(File f : files){
                // 如果是目录,继续递归
                if(f.isDirectory()){
                    find(f);
                }else if(f.isFile()){
                    // 当是文件的时候,再筛选是否符合我们的条件,符合就加入最终集合
                    if(f.getName().equals("Test.class")){
                        list.add(f.getCanonicalPath());
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    三、普通文件(文本&非文本)的内容读取

    在这里插入图片描述

    1.InputStream抽象类

    java.io.InputStream

    (1)常用方法:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IcRjCGxF-1660788981932)(C:\Users\星\AppData\Roaming\Typora\typora-user-images\1652093640429.png)]

    各种实现类

    FileInputStream 、SocketInputStream

    2.FileInputStream

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vt3qOzrr-1660788981933)(C:\Users\星\AppData\Roaming\Typora\typora-user-images\1652094067834.png)]

    实例:

    public class ReadFile1 {
        public static void main(String[] args) throws IOException {
    //        创建方式一
            InputStream is = new FileInputStream("..\\test.txt");
    //        创建方式二
            File file = new File("..\\test.txt");
            InputStream iss = new FileInputStream(file);
            byte[] b = new byte[5];
            int n = iss.read(b);
    //        不想自己关闭,也可以把上面的语句放在try中,try语句执行完会自动关闭
            iss.close();
            System.out.println(n);
            System.out.println(Arrays.toString(b));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    打印输出文件中的所有内容

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    /**用read方法打印输出文件中的全部内容
     * @author sunny
     * @date 2022/05/09 19:33
     **/
    public class ReadFile2 {
        public static void main(String[] args) throws IOException {
            try(InputStream is = new FileInputStream("..\\test.txt")){
              while(true){
                  int n = is.read();
                  if(n == -1){
                      break;
                  }
                  System.out.println(n);
              }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Arrays;
    
    /**用byte数组打印输出所有数据
     * @author sunny
     * @date 2022/05/09 19:36
     **/
    public class ReafFile3 {
        public static void main(String[] args) throws IOException {
            try(InputStream is = new FileInputStream("..\\test.txt")){
                byte[] b = new byte[2];
                while(true){
                    int n = is.read(b);
                    if(n == -1){
                        break;
                    }
                    System.out.println(new String(b));
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    【注意】byte数组一般用1024个,减少去硬盘的读取,而且1024恰好是一整块

    【注意】UTF-8中一个字符(数字、英文)占一个字节,中文占三个字节

    【注意】new Scanner 就是InputStream

    3.借助Scanner类从文件读中文字符

    就是将字节码文件转为字符文件

    • 用Scanner类
    public class ReadText {
        public static void main(String[] args) throws IOException {
            InputStream is = new FileInputStream("..\\test.txt");
    //        传入Scanner类,还可以规定编码格式
            Scanner scan = new Scanner(is,"UTF-8");
            while(scan.hasNextLine()){
                System.out.println(scan.nextLine());
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • Reader 和 InputStream 地位等价

    4.OutputStream抽象类

    write方法+close+flush

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eUhwbffu-1660788981933)(C:\Users\星\AppData\Roaming\Typora\typora-user-images\1652097945802.png)]

    字符写入文件示例:

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    /**将字符写入文件
     * @author sunny
     * @date 2022/05/09 20:29
     **/
    public class WriteFile1 {
        public static void main(String[] args) throws IOException {
            try(OutputStream os = new FileOutputStream("..\\write2.txt")){
                byte[] b = {'h','h','m','\r','\n','h'};
                os.write(b);
                os.flush();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    5.借助Print类写入文件

    转为中文字符,用print方法写入

    import java.io.*;
    
    /**用之前的print方法写入文件
     * @author sunny
     * @date 2022/05/09 20:06
     **/
    public class WriteText {
        public static void main(String[] args) throws IOException {
            try(OutputStream os = new FileOutputStream("..\\write.txt")){
                try(Writer writer = new OutputStreamWriter(os,"utf-8")){
                    try(PrintWriter printWriter = new PrintWriter(writer)){
                        printWriter.println("啦啦啦啦");
                        printWriter.flush();
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    小游戏:

    👻👻👻文本替换

    import java.io.*;
    import java.util.Scanner;
    
    /**文本替换,将test文件中的哈喽全部替换为你好,将替换后的文本全部写入文件replace中
     * @author sunny
     * @date 2022/05/09 20:38
     **/
    public class ReplaceText {
        public static void main(String[] args) throws IOException {
            try (InputStream is = new FileInputStream("..\\test.txt")) {
                try (Scanner scanner = new Scanner(is, "utf-8")) {
                    try (OutputStream os = new FileOutputStream("..\\replace.txt")) {
                        try (Writer writer = new OutputStreamWriter(os, "utf-8")) {
                            try (PrintWriter printWriter = new PrintWriter(writer)) {
                                while (scanner.hasNextLine()) {
                                    String str1 = scanner.nextLine();
                                    String str2 = str1.replace("哈喽", "你好");
                                    printWriter.println(str2);
                                }
                                printWriter.flush();
                            }
                        }
                    }
    
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    👻👻👻文件的复制(任意类型的文件)

    import java.io.*;
    
    /**任意文件的复制,如本例中图片的复制
     * @author sunny
     * @date 2022/05/09 20:47
     **/
    public class CopyFile {
        public static void main(String[] args) throws IOException {
            try(InputStream is = new FileInputStream("..\\111.png")){
                try(OutputStream os = new FileOutputStream("..\\copy111.png")){
                    byte[] b = new byte[1024];
                    while(true){
                        int n = is.read(b);
                        if(n == - 1){
                            break;
                        }
                        os.write(b,0,n);
                    }
                    os.flush();
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    重点

    小结:从文件中读写为符合之前标准输入输出的习惯,我们可以借助Scanner类,借助PrintWriter类,将输入输出转换为之前的scanner.nextLine()和println()

    public class ReadText {
        public static void main(String[] args) throws IOException {
            InputStream is = new FileInputStream("..\\test.txt");
    //        传入Scanner类,还可以规定编码格式
            Scanner scan = new Scanner(is,"UTF-8");
            while(scan.hasNextLine()){
                System.out.println(scan.nextLine());
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    import java.io.*;
    
    /**用之前的print方法写入文件
     * @author sunny
     * @date 2022/05/09 20:06
     **/
    public class WriteText {
        public static void main(String[] args) throws IOException {
            try(OutputStream os = new FileOutputStream("..\\write.txt")){
                try(Writer writer = new OutputStreamWriter(os,"utf-8")){
                    try(PrintWriter printWriter = new PrintWriter(writer)){
                        printWriter.println("啦啦啦啦");
                        printWriter.flush();
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    java计算机毕业设计物业服务管理系统源程序+mysql+系统+lw文档+远程调试
    Android PreferenceActivity添加ToolBar
    超级详细Spring AI+ChatGPT(java接入OpenAI大模型)
    PM 的个人核心竞争力
    Python基本数据类型
    深度神经网络预测模型,神经网络预测未来数据
    [C题目]力扣142. 环形链表 II
    Java实习生面试题汇总
    手把手教你如何使用YOLOV5训练自己的数据集
    FileZilla Server.xml 如何配置
  • 原文地址:https://blog.csdn.net/m0_58652786/article/details/126400363