javaseday28 IO

news2024/9/21 19:30:06

IO流

IO流;存储和读取数据的解决方案。

纯文本文件:Windows自带的记事本打开能读懂的文件,word和Excel不是纯文本文件,txt和md是纯文本文件。

小结

 IO流体系

FileOutputStream

public class Demo1 {
    public static void main(String[] args) throws IOException {
        //创建对象
        FileOutputStream fos = new FileOutputStream("javaseday28Io\\a.txt");
        //传输数据(字节),根据asicii码为 a
        fos.write(97);
        //关闭资源
        fos.close();
    }
}

a

FileOutputStream细节

 

FileOutputStream写数据的3种方式

public class Demo2 {
    public static void main(String[] args) throws IOException {
        //创建对象
        FileOutputStream fos = new FileOutputStream("javaseday28Io\\a.txt");
        //传输数据(字节),根据asicii码为 a
//        fos.write(97);
        //传输byte数组
        byte[] bytes = {97,98,99,100,101,102};
//        fos.write(bytes);
        fos.write(bytes,1,3);
        /**
         * 参数一:要写入的数组
         * 参数二:写入的起始索引
         * 参数三:写入的个数
         */
        //关闭资源
        fos.close();
    }
}

换行和续写

public class Demo3 {
    public static void main(String[] args) throws IOException {
        /**
         * 不同的操作系统的换行符号不同
         * windos \r\n
         *linux \n
         * mac \r
         */
        /**
         * 续写 在创建FileOutputStream对象时调用不用的构造方法即可
         * FileOutputStream fos = new FileOutputStream("javaseday28Io\\a.txt",true);即为保存数据的续写
         */
        //创建对象
        FileOutputStream fos = new FileOutputStream("javaseday28Io\\a.txt",true);
        //传输数据(字节),根据asicii码为 a
        //换行和续写
        //换行
        String s1 = "duzhelaiyizhengshui";
        byte[] bytes1 = s1.getBytes();
        fos.write(bytes1);
        //将换行符号使用字符串表示并写入

        String s2 = "\r\n";
        byte[] bytes2 = s2.getBytes();
        fos.write(bytes2);
        String s3 = "666";
        byte[] bytes3 = s3.getBytes();
        fos.write(bytes3);

        //关闭资源
        fos.close();
    }
}

FileOutputStream的小结

FileInputStream

public class Demo1 {
    public static void main(String[] args) throws IOException {
        /**
         * 如果读取到空值则返回-1
         */
        FileInputStream fos = new FileInputStream("javaseday28Io\\a.txt");
        int r1 = fos.read();
        System.out.println((char) r1);
        int r2 = fos.read();
        System.out.println((char) r2);

        int r3 = fos.read();
        System.out.println((char) r3);

        int r4= fos.read();
        System.out.println((char) r4);

        int r5 = fos.read();
        System.out.println((char) r5);

        int r6 = fos.read();//-1
        System.out.println(r6);

        fos.close();
    }
}

细节

FileInputStream的循环读取

public class Demo2 {
    public static void main(String[] args) throws IOException {
        /**
         * 如果读取到空值则返回-1
         */
        FileInputStream fos = new FileInputStream("javaseday28Io\\a.txt");
        int r1;
        while ((r1 = fos.read()) != -1){
            System.out.println((char)r1);
        }


        fos.close();
    }
}

FileInputStream的拷贝文件

public class Demo3 {
    public static void main(String[] args) throws IOException {
        /**
         * 如果读取到空值则返回-1
         */
        FileInputStream fis = new FileInputStream("C:\\Users\\20724\\Desktop\\123.jpg");
        FileOutputStream fos = new FileOutputStream("javaseday28Io\\123.jpg");
        int r1;
        //将读取到的信息写入目标文件
        while ((r1 = fis.read()) != -1){
            fos.write(r1);
        }
        //关闭资源
        fos.close();
        fis.close();
    }
}

文件拷贝的弊端和解决方法

文件拷贝单个字符拷贝较慢,可以使用数组进行拷贝。

public class Demo4 {

        public static void main(String[] args) throws IOException {
            /**
             * 如果读取到空值则返回-1
             */


            FileInputStream fis = new FileInputStream("C:\\Users\\20724\\Desktop\\123.jpg");
            FileOutputStream fos = new FileOutputStream("javaseday28Io\\123.jpg");
            //创建一个5MB的数组存储数据
            byte[] bytes = new byte[1024*1024*5];
            //记录每次数组中写入的数据的长度,一遍输出的时候知道输出几个字符
            int len;
            //将读取到的信息写入目标文件
            //将数据读取到数组是是将读取的字符覆盖数组中已有的字符,如果没有被覆盖到就会保留
            while ((len = fis.read(bytes)) != -1){
                //由于没有被覆盖到就会保留,所以向文件写入时要根据读取数据的长度写入
                fos.write(bytes,0,len);
            }
            //关闭资源
            fos.close();
            fis.close();
        }

}

IO流中不同JDK版本捕获异常的方式

基本写法:
public class Demo5 {
    public static void main(String[] args) throws IOException {
        /**
         * 如果读取到空值则返回-1
         */

        long start = System.currentTimeMillis();

        //由于代码块中的变量只能在本块中访问,为了在final中关闭流因此定义在外面。
        //定义之后不赋值会出现未初始化错误所以赋值为null
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("C:\\Users\\20724\\Desktop\\123.jpg");
            fos = new FileOutputStream("javaseday28Io\\123.jpg");
            byte[] bytes = new byte[1024*1024*5];
            int len;
            while ((len = fis.read(bytes)) != -1){
                fos.write(bytes,0,len);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源
            //判断是否为空,即是否成功创建了流对象
            if (fos != null){
                //捕获关闭流时的异常
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            //判断是否为空,即是否成功创建了流对象
            if (fis != null){
                //捕获关闭流时的异常
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            
            }
        }
        long end = System.currentTimeMillis();
        System.out.println((end-start)/1000.0);
    }
}

public class Demo6 {

    public static void main(String[] args) throws IOException {
        /**
         * 如果读取到空值则返回-1
         */
        /**
         * JDK7 的写法
         * 不需要关闭流
         */

        try(FileInputStream fis = new FileInputStream("C:\\Users\\20724\\Desktop\\123.jpg");
            FileOutputStream fos = new FileOutputStream("javaseday28Io\\123.jpg")) {
            byte[] bytes = new byte[1024*1024*5];
            int len;
            while ((len = fis.read(bytes)) != -1){
                fos.write(bytes,0,len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
public class Demo7 {
    public static void main(String[] args) throws IOException {
        /**
         * 如果读取到空值则返回-1
         */
        /**
         * JDK9 的写法
         * 不需要关闭流
         */
        FileInputStream fis = new FileInputStream("C:\\Users\\20724\\Desktop\\123.jpg");
        FileOutputStream fos = new FileOutputStream("javaseday28Io\\123.jpg");
        try(fis;fos) {
            byte[] bytes = new byte[1024*1024*5];
            int len;
            while ((len = fis.read(bytes)) != -1){
                fos.write(bytes,0,len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

字符集

ASCII

GBK

小结

Unicode

小结

出现乱码的原因

扩展

java中的编码和解码

public class Demo1 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "hao读者";
        //使用默认编码方法即utf8
        byte[] bytes1 = str.getBytes();
        System.out.println(Arrays.toString(bytes1));
        //[104, 97, 111, -24, -81, -69, -24, -128, -123]
        //使用GBK编码
        byte[] bytes2 = str.getBytes("GBK");
        System.out.println(Arrays.toString(bytes2));
        //[104, 97, 111, -74, -63, -43, -33]

        //解码
        String s2 = new  String(bytes1);
        System.out.println(s2);
        //hao读者
        //使用错误的解码方式
        String s3 = new  String(bytes1,"GBK");
        System.out.println(s3);
        //出现乱码 hao璇昏��

        String s4 = new  String(bytes2,"GBK");
        System.out.println(s4);
        //hao读者
    }
}

字符流

FileReader

    public static void main(String[] args) throws IOException {
        /*
            第一步:创建对象
            public FileReader(File file)        创建字符输入流关联本地文件
            public FileReader(String pathname)  创建字符输入流关联本地文件

            第二步:读取数据
            public int read()                   读取数据,读到末尾返回-1
            public int read(char[] buffer)      读取多个数据,读到末尾返回-1

            第三步:释放资源
            public void close()                 释放资源/关流
        */

        //1.创建对象并关联本地文件
        FileReader fr = new FileReader("myio\\a.txt");
        //2.读取数据 read()
        //字符流的底层也是字节流,默认也是一个字节一个字节的读取的。
        //如果遇到中文就会一次读取多个,GBK一次读两个字节,UTF-8一次读三个字节

        //read()细节:
        //1.read():默认也是一个字节一个字节的读取的,如果遇到中文就会一次读取多个
        //2.在读取之后,方法的底层还会进行解码并转成十进制。
        //  最终把这个十进制作为返回值
        //  这个十进制的数据也表示在字符集上的数字
        //  英文:文件里面二进制数据 0110 0001
        //          read方法进行读取,解码并转成十进制97
        //  中文:文件里面的二进制数据 11100110 10110001 10001001
        //          read方法进行读取,解码并转成十进制27721

        // 我想看到中文汉字,就是把这些十进制数据,再进行强转就可以了

        int ch;
        while((ch = fr.read()) != -1){
            System.out.print((char)ch);
        }

        //3.释放资源
        fr.close();

    }

带参数的Reader方法

    public static void main(String[] args) throws IOException {
        /*
            第一步:创建对象
            public FileReader(File file)        创建字符输入流关联本地文件
            public FileReader(String pathname)  创建字符输入流关联本地文件

            第二步:读取数据
            public int read()                   读取数据,读到末尾返回-1
            public int read(char[] buffer)      读取多个数据,读到末尾返回-1

            第三步:释放资源
            public void close()                 释放资源/关流
        */


        //1.创建对象
        FileReader fr = new FileReader("myio\\a.txt");
        //2.读取数据
        char[] chars = new char[2];
        int len;
        //read(chars):读取数据,解码,强转三步合并了,把强转之后的字符放到数组当中
        //空参的read + 强转类型转换
        while((len = fr.read(chars)) != -1){
            //把数组中的数据变成字符串再进行打印
            System.out.print(new String(chars,0,len));
        }
        //3.释放资源
        fr.close();

    }

FileWriter

构造方法

成员方法

书写细节

    public static void main(String[] args) throws IOException {
        //保存文件中的数据
        FileWriter fw = new FileWriter("javaseday28Io\\a.txt",true);

//        fw.write(97);
        String st = "asd哈哈哈";
//        fw.write(st);
//        fw.write(st,2,4);
        char[] chars = {'a','c','b','你','好'};
//        fw.write(chars);
        fw.write(chars,1,4);

        fw.close();
    }

字符流的原理解析

输入流解析

    public static void main(String[] args) throws IOException {

        FileReader fr = new FileReader("myio\\b.txt");
        fr.read();//会把文件中的数据放到缓冲区当中

        //清空文件
        FileWriter fw = new FileWriter("myio\\b.txt");

        //请问,如果我再次使用fr进行读取
        //会读取到数据吗?

        //会把缓冲区中的数据全部读取完毕

        //正确答案:
        //但是只能读取缓冲区中的数据,文件中剩余的数据无法再次读取
        int ch;
        while((ch = fr.read()) != -1){
            System.out.println((char)ch);
        }


        fw.close();
        fr.close();


    }
输出流解析

flush和close方法

    public static void main(String[] args) throws IOException {


        FileWriter fw = new FileWriter("myio\\a.txt");


       fw.write("我的同学各个都很厉害");
       fw.write("说话声音很好听");

       fw.flush();

       fw.write("都是人才");
       fw.write("超爱这里哟");

      fw.close();

       fw.write("B站");

    }

使用场景

综合练习

练习一:拷贝

public class Test {
    public static void main(String[] args) throws IOException {
        /**
         * 拷贝文件
         */
        //目标文件夹
        File f1 = new File("C:\\Users\\20724\\Desktop\\FileTest");
        File f2= new File("C:\\Users\\20724\\Desktop\\123");
        copyfile(f1,f2);
    }

    //复制方法
    private static void copyfile(File f1, File f2) throws IOException {
        //创建文件夹防止无法存放文件
        f2.mkdir();
        //使用递归的方法
        //遍历数组
        //判断
        File[] files = f1.listFiles();

        for (File file : files) {
            if (file.isFile()){
                FileInputStream fis = new FileInputStream(file);
                FileOutputStream fos = new FileOutputStream(new File(f2,file.getName()));

                int len;
                byte[] bytes = new byte[1024];
                while ((len = fis.read(bytes)) != -1){
                    fos.write(bytes,0,len);
                }

                fos.close();
                fis.close();

            }else {
                //为文件夹进行递归
                copyfile(file,new File(f2,file.getName()));
            }
        }
    }
}

练习二:文件加密

public class Test {
    public static void main(String[] args) throws IOException {
        //文件加密,解密都可以使用只需要修改输入文件和输出文件
        FileInputStream fis = new FileInputStream("javaseday28Io\\cnpy.jpg");
        FileOutputStream fos = new FileOutputStream("javaseday28Io\\678.jpg");

        int len;

        while (( len = fis.read()) != -1){
            fos.write(len ^ 1920);
        }

        fos.close();
        fis.close();
    }
}

练习三:修改文件数据

方法一:
public class Test1 {
    public static void main(String[] args) throws IOException {
        //普通方法写

        //获取文件,读取数据
        FileReader fr = new FileReader("javaseday28Io\\a.txt");
        //接受数据
        StringBuilder sb = new StringBuilder();
        int len;
        while ((len = fr.read()) != -1){
            sb.append((char)len);
        }
        fr.close();
        String string = sb.toString();
        System.out.println();

        //修改数据
        //读去数据
        ArrayList<Integer> list = new ArrayList<>();
        String[] split = string.split("-");
        for (String s : split) {
            list.add(Integer.parseInt(s));
        }

        //修改数据
        Collections.sort(list);

        //写入数据
        //获取写入文件的地址
        FileWriter fw = new FileWriter("javaseday28Io\\b.txt");
        for (int i = 0; i < list.size(); i++) {
            if (i!=list.size()-1){
                fw.write(list.get(i)+"");
                fw.write("-");
            }else {
                fw.write(list.get(i)+"");
            }
        }
        fw.close();
    }
}
方法二:
public class Test2 {
    public static void main(String[] args) throws IOException {
        //普通方法写

        //获取文件,读取数据
        FileReader fr = new FileReader("javaseday28Io\\a.txt");
        //接受数据
        StringBuilder sb = new StringBuilder();
        int len;
        while ((len = fr.read()) != -1){
            sb.append((char)len);
        }
        fr.close();

        //修改数据
        //读去数据
            //使用Stream流进行操作
        Integer[] array = Arrays.stream(sb.toString().split("-"))
                //.map(new Function<String, Integer>() {
                //                    @Override
                //                    public Integer apply(String s) {
                //                        return Integer.parseInt(s);
                //                    }
                //                })
                //将String类型转换为Int类型,Map进行类型转换
                .map(Integer::parseInt)
                .sorted()
                .toArray(Integer[]::new);


        //写入数据
        //获取写入文件的地址
        FileWriter fw = new FileWriter("javaseday28Io\\b.txt");
        //将 , 的间隔符装换位 - 的间隔符
        String s = Arrays.toString(array).replace(", ","-");
        //将头尾的中括号剪裁掉
        String res = s.substring(1, s.length() - 1);
        fw.write(res);
        fw.close();
    }
}

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

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

相关文章

【学习笔记】 使用AD24完成相同电路的自动布线布局(相同模块布局布线ROOM布线快速克隆)

【学习笔记】 使用AD24完成相同电路的自动布线布局 一、适用基本条件二、基于ROOM的自动布局/布线的方法三、可能出现的报错四、ROOM自动布局的一些优点和缺点 当面对多个相同电路模块时&#xff0c;使用 ROOM 可以一次性对一个模块进行精心布局&#xff0c;然后将该布局快速复…

2024 研究生数学建模竞赛(C题)建模秘籍|数据驱动下磁性元件的磁芯损耗建模|文章代码思路大全

铛铛&#xff01;小秘籍来咯&#xff01; 小秘籍团队独辟蹊径&#xff0c;运用数据拟合&#xff0c;方差分析&#xff08;ANOVA&#xff09;&#xff0c;特征提取&#xff0c;多目标优化等强大工具&#xff0c;构建了这一题的详细解答哦&#xff01; 为大家量身打造创新解决方案…

vs2022快捷键异常不起作用解决办法

安装了新版本的vs2022&#xff0c;安装成功后&#xff0c;发现快捷键发生异常&#xff0c;之前常用的快捷键要么发生改变&#xff0c;要么无法使用&#xff0c;比如原来注释代码的快捷键是ctrlec&#xff0c;最新安装版本变成了ctrlkc&#xff0c;以前编译代码的快捷键是F6或者…

go webapi上传文件 部属到linux

go厉害的地方&#xff0c;linux服务器上无需安装任务依赖就可以运行&#xff0c;大赞&#xff01; 一、编译 #在Goland中cmd中执行 go env -w GOARCHamd64 go env -w GOOSlinux go build main.go # 切换回来 否则无法运行 go env -w GOOSwindows go run main.go 拷贝到linux服…

ubuntu如何进行自动mount硬盘(简易法)

1. 找到你ubuntu的disk工具 2. 选中你要mount的盘 3. 点击那个设置按钮 4. 选择edit mount options 5. disable user session defaults 6, 填写Mount Point就可以了&#xff0c; 最后输入一次密码&#xff0c;重启设备就搞定了

DOG:知识图谱大模型问答的迭代交互式推理,克服长路径和假阳性关系挑战

DOG&#xff1a;知识图谱大模型问答的迭代交互式推理&#xff0c;克服长路径和假阳性关系挑战 秒懂大纲提出背景解法拆解全流程优化和医学关系 创意 秒懂大纲 ├── DoG框架【主题】 │ ├── 背景【研究背景】 │ │ ├── LLMs的局限性【问题描述】 │ │ │ …

pgvector docker版安装;稀疏向量使用;psycopg2 python连接使用

参看: https://cloud.tencent.com/developer/article/2359831 https://hub.docker.com/r/pgvector/pgvector/tags https://github.com/pgvector/pgvector 一、安装 拉取0.7版本 docker pull pgvector/pgvector:0.7.4-pg16运行: docker run --name pgvector -v $(pwd)/dat…

OpenLayers 开源的Web GIS引擎 - 地图初始化

在线引用&#xff1a; 地址&#xff1a;OpenLayers - Get the Code 离线引用&#xff1a; 下载地址&#xff1a;Releases openlayers/openlayers GitHub v10.0.0版本 地图初始化代码&#xff1a; <!DOCTYPE html> <html lang"en"> <head><…

Spring Boot 入门:解锁 Spring 全家桶

前言 Spring 全家桶是现代 Java 开发者不可或缺的工具集&#xff0c;它提供了从轻量级的框架到微服务架构的完整支持。本文将带你快速了解 Spring 框架、核心概念如 IoC&#xff08;控制反转&#xff09;和 AOP&#xff08;面向切面编程&#xff09;&#xff0c;并深入介绍 Sp…

Java项目实战II基于Java+Spring Boot+MySQL的网上租贸系统设计与实现(开发文档+源码+数据库)

目录 一、前言 二、技术介绍 三、系统实现 四、论文参考 五、核心代码 六、源码获取 全栈码农以及毕业设计实战开发&#xff0c;CSDN平台Java领域新星创作者&#xff0c;专注于大学生项目实战开发、讲解和毕业答疑辅导。获取源码联系方式请查看文末 一、前言 "随着…

hpux B.11.31 安装 JDK(详细步骤、多图预警)

目录 零、测试环境 一、获取 JDK 安装包 二、安装 JDK 1、操作指南 2、安装流程 &#xff08;1&#xff09;选中 Java JDK &#xff08;2&#xff09;&#xff08;可选&#xff09;选择安装目录 &#xff08;3&#xff09;点击安装 &#xff08;4&#xff09;&#xf…

CefSharp_Vue交互(Element UI)_WinFormWeb应用(4)--- 最小化最大化关闭窗体交互(含示例代码)

一、效果预览 实现功能,通过vue页面模仿窗体的三个功能按钮实现最小化最大化关闭功能 1.1 预览 1.2 代码 页面代码

【Linux】简易日志系统

目录 一、概念 二、可变参数 三、日志系统 一、概念 一个正在运行的程序或系统就像一个哑巴&#xff0c;一旦开始运行我们很难知晓其内部的运行状态。 但有时在程序运行过程中&#xff0c;我们想知道其内部不同时刻的运行结果如何&#xff0c;这时一个日志系统可以有效的帮…

【算法】2022年第十三届蓝桥杯大赛软件类省赛Java大学C组真题

个人主页&#xff1a;NiKo 算法专栏&#xff1a;算法设计与分析 目录 题目 2680:纸张尺寸 题目 2664:求和 题目 2681: 矩形拼接 题目 2665: 选数异或 题目 2682: GCD 题目 2667: 青蛙过河 题目 2683: 因数平方和 题目 2668: 最长不下降子序列 题目 2680:纸张尺寸 题目…

2024普通高校大学生竞赛

2024年A类竞赛(全国普通高校大学生竞赛)目录 结合A类竞赛目录选择一些大学高质量竞赛 大学生竞赛 大学生竞赛中国国际大学生创新大赛ACM-ICPC国际大学生程序设计竞赛中国大学生计算机设计大赛中国高校计算机大赛蓝桥杯全国软件和信息技术专业人才大赛百度之星程序设计大赛全国…

2016年国赛高教杯数学建模A题系泊系统的设计解题全过程文档及程序

2016年国赛高教杯数学建模 A题 系泊系统的设计 近浅海观测网的传输节点由浮标系统、系泊系统和水声通讯系统组成&#xff08;如图1所示&#xff09;。某型传输节点的浮标系统可简化为底面直径2m、高2m的圆柱体&#xff0c;浮标的质量为1000kg。系泊系统由钢管、钢桶、重物球、…

KDD 2024论文分享┆STAMP:一种基于时空图神经网络的微服务工作负载预测方法

论文分享简介 本推文详细介绍了一篇最新论文成果《Integrating System State into Spatio Temporal Graph Neural Network for Microservice Workload Prediction》&#xff0c;论文的作者包括&#xff1a;上海交通大学先进网络实验室: 罗旸、高墨涵、余哲梦&#xff0c;高晓沨…

gh-ost

优质博文&#xff1a;IT-BLOG-CN 一、gh-ost的作用 gh-ost是由Github提供的Online DDL工具&#xff0c;使用binlog代替之前的触发器做异步增量数据同步&#xff0c;从而降低主库负载。 基于触发器的Online DDL工具原理&#xff1a; 【1】根据原表结构执行alter语句&#xff…

抖音矩阵系统源码搭建,矩阵系统贴牌,矩阵工具开源

1. 抖音短视频矩阵系统 抖音短视频矩阵系统&#xff0c;是指通过抖音平台&#xff0c;以矩阵的形式进行短视频创作、发布和传播的一种模式。它以多样化的内容、丰富的表现形式、高度的专业化和协同性&#xff0c;吸引了大量用户和创作者的关注。 2. 短视频矩阵系统的优势 2.1 …

从技术打磨到产品验证:读《程序员修炼之道》的务实之道

在编程世界里&#xff0c;技术的打磨往往像是工匠雕琢作品&#xff0c;但若无法转化为产品的成功&#xff0c;所有的精致都不过是空中楼阁。读《程序员修炼之道》时&#xff0c;我深刻意识到&#xff0c;务实不仅仅是技术的选择&#xff0c;更是产品迭代和商业模式成功的关键。…