10 IO实例

news2024/10/6 2:25:35

IO

1 流

流可以认为是一条通道,它可以将数据从源端传送到目的地。

例如将程序中的某些数据写入文件,或将文件中的某些数据读入程序。

Java中数据的操作是以“流”的方式进行。

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

Java中的“流”是一个具体的Java对象,该对象提供一些方法进行数据的传递。

Java中用来创建流对象的类有很多,这些类创建出来的对象所应用的场景是不同的。

Java中的流都声明再java.io 这个包中。

流的分类:

  • 按照输入输出分类:
    • 输入流
    • 输出流
  • 按照传输数据单元分类:
    • 字节流
    • 字符流
  • 按照功能分类:
    • 节点流
    • 处理流

流的类都是从一下四个抽象类派生的

在这里插入图片描述

2 文件流

程序读写文件的流,功能属于节点流。

文件字节流文件字符流
文件输入流FileInputStreamFileReader
文件输出流FileOutputStreamFileWriter

2.1 FileOutputStream

public class File_io_v1 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fo = new FileOutputStream("D:\\Java\\eclipsefile\\Java-study\\IO_test\\out.txt" );
        String str = "hello world!";
        byte[] bstr = str.getBytes();
        fo.write(bstr);
        fo.flush();
        fo.close();
    }
}

sout(fo)的输出是java.io.FileOutputStream@16b98e56

public class File_io_v2 {
    public static void main(String[] args) {
        FileOutputStream fo = null;
        try{
            fo = new FileOutputStream("D:\\Java\\eclipsefile\\Java-study\\IO_test\\out2.txt");
            String str = "skdjhjkshdf";
            byte[] bstr = str.getBytes();
            fo.write(bstr);
        } catch (FileNotFoundException e1) {
            System.out.println("文件无法打开");
            e1.printStackTrace();
        } catch (IOException e2) {
            System.out.println("IO错误");
            e2.printStackTrace();
        }catch(Exception e3){
            System.out.println("危险危险危险!");
            e3.printStackTrace();
        }finally {
            try{
                if(fo != null){
                    fo.close();
                }
            } catch (IOException e) {
                System.out.println("危险危险危险!");
                e.printStackTrace();
            }
        }
    }
}

2.2 FileReader

public class File_io_v3 {
    public static void main(String[] args) throws IOException {
        FileReader fi = new FileReader("D:\\Java\\eclipsefile\\Java-study\\IO_test\\out2.txt");
        int r = fi.read();
        String str = "";
        while(r != -1){
            str = str + (char) r;
            System.out.println((char) r);
            r = fi.read();
        }
        System.out.println(str);
        fi.close();
    }
}
public class File_io_v4 {
    public static void main(String[] args) {
        FileReader fr1 = null;
        FileReader fr2 = null;
        FileWriter fw1 = null;
        FileWriter fw2 = null;
        try {
            fr1 = new FileReader("D:\\Java\\eclipsefile\\Java-study\\IO_test\\in.txt");
            fr2 = new FileReader("D:\\Java\\eclipsefile\\Java-study\\IO_test\\in2.txt");
            fw1 = new FileWriter("D:\\Java\\eclipsefile\\Java-study\\IO_test\\out.txt");
            fw2 = new FileWriter("D:\\Java\\eclipsefile\\Java-study\\IO_test\\out2.txt");
            int r1;
            int r2;
            while ((r1 = fr1.read()) != -1){
                System.out.println((char) r1);
                r1 = fr1.read();
            }
            fw1.write("衬布不易");
            fw1.flush();
            while((r2 = fr2.read()) != -1){
                fw2.write((char) r2);
            }
            fw2.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try{
                if(fr1 != null)fr1.close();
                if(fr2 != null)fr2.close();
                if(fw1 != null)fw1.close();
                if(fw2 != null)fw2.close();
            }catch(Exception e){e.printStackTrace();}
        }
    }
}

3 缓冲流

是对节点流进行包装的流。功能上属于处理流,提供了增强节点流功能的方法。

最常用是提供了缓冲字符流的读写一行的功能

缓冲字节流缓冲字符流
缓冲输入流BufferedInputStreamBufferedReader
缓冲输出流BufferedOutputStreamBufferedWriter
public class Buffer_io_v1 {
    public static void main(String[] args) {
        FileReader fr = null;
        FileWriter fw = null;
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            fr = new FileReader("D:\\Java\\eclipsefile\\Java-study\\IO_test\\in2.txt");
            fw = new FileWriter("D:\\Java\\eclipsefile\\Java-study\\IO_test\\out2.txt");
            br = new BufferedReader(fr);
            bw = new BufferedWriter(fw);
            String str = null;
            while ((str = br.readLine()) != null){
                System.out.println(str);
            }
            System.out.println("输入流结束");
            bw.write("庆历四年春,");
            bw.newLine();
            bw.write("滕子京谪守巴陵郡。");
            bw.newLine();
            bw.write("越明年,政通人和,百废具兴。");
            bw.newLine();
            bw.write("乃重修岳阳楼,增其旧制,");
            bw.newLine();
            bw.write("刻唐贤今人诗赋于其上。");
            bw.newLine();
            bw.write("属予作文以记之");
            bw.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (fr != null)fr.close();
                if (fw != null)fw.close();
                if (br != null)br.close();
                if (bw != null)bw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

4 转换流

将字节流转换为字符流,属于是处理流

其中字节流可以操作所有类型的文件包括音频视频和图片,而字符流只能操作纯文本文件,如java文件,txt文件等。

输入转换流InputStreamReader
输出转换流OutputStreamWriter
public class Convert_io_v1 {
    public static void main(String[] args) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        InputStreamReader ir = null;
        OutputStreamWriter ow = null;
        try {
            fi = new FileInputStream("D:\\Java\\eclipsefile\\Java-study\\IO_test\\in2.txt");
            fo = new FileOutputStream("D:\\Java\\eclipsefile\\Java-study\\IO_test\\out2.txt");
            ir = new InputStreamReader(fi);
            ow = new OutputStreamWriter(fo);
            int r;
            while ((r = ir.read()) != -1){
                System.out.println((char) r);
                ow.write(r);
            }
            ow.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try{
                if(fi != null)fi.close();
                if(fo != null)fo.close();
                if(ir != null)ir.close();
                if(ow != null)ow.close();
            }catch(Exception e){e.printStackTrace();}
        }
    }
}

5 数据流

可以对机器无关的原始数据类型(int,double)进行读写。不需要关心数据的字节数。属于处理流

输入数据流DataInputStream
输出数据流DataOutputStream
public class Data_io_v1 {
    public static void main(String[] args) {
        FileOutputStream fo  = null;
        DataOutputStream doo = null;
        try {
            fo = new FileOutputStream("D:\\Java\\eclipsefile\\Java-study\\IO_test\\out.txt");
            doo = new DataOutputStream(fo);
            fo.write(65);
            fo.write(65+256);
            fo.flush();
            doo.write(65);
            doo.write(65+256);
            doo.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try{
                if(fo != null)fo.close();
                if (doo != null)doo.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

    }
}

6 打印流

打印形式的输出流,属于处理流

打印字节流打印字符流
PrintStreamPrintWrite
public class Print_io_v1 {
    public static void main(String[] args) {
        FileOutputStream fo = null;
        DataOutputStream doo = null;
        PrintWriter pw = null;
        try {
            fo = new FileOutputStream("D:\\Java\\eclipsefile\\Java-study\\IO_test\\out.txt");
            doo = new DataOutputStream(fo);
            pw = new PrintWriter(fo);
            fo.write(65);
            fo.flush();
            doo.write(65);
            doo.flush();
            pw.write(65);
            pw.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (fo != null)fo.close();
                if (doo != null)doo.close();
                if(pw != null)pw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
public class Print_io_v2 {
    public static void main(String[] args) {
        FileOutputStream fo = null;
        PrintWriter pw = null;
        try {
            fo = new FileOutputStream("D:\\Java\\eclipsefile\\Java-study\\IO_test\\out.txt");
            pw = new PrintWriter(fo);
            pw.println("hello world");
            pw.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (fo != null)fo.close();
                if(pw != null)pw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

7 对象流

可以进行对象的写入和读出。进行读写的对象要是可序列化的。属于处理流。

如果创建对象的类是实现了Serializable接口的类,则对象是可序列化的。

对象输出流对象输入流
ObjectInputStreamObjectInputStream
public class Object_io_v1 {
    public static void	main(String [] args){
        FileOutputStream fo = null;
        FileInputStream fi = null;
        ObjectOutputStream oo = null;
        ObjectInputStream oi = null;
        try{
            fo = new FileOutputStream("D:\\Java\\eclipsefile\\Java-study\\IO_test\\at.txt");
            fi = new FileInputStream("D:\\Java\\eclipsefile\\Java-study\\IO_test\\at.txt");
            oo = new ObjectOutputStream(fo);
            oi = new ObjectInputStream(fi);
            oo.writeObject(new Rect(3,5));
            oo.flush();
            Rect r = (Rect)oi.readObject();
            System.out.println(r.area());
        }catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try{
                if(oo != null)oo.close();
                if(oi != null)oi.close();
                if(fo != null)fo.close();
                if(fi != null)fi.close();
            }catch(Exception e){e.printStackTrace();}
        }
    }
}
class Rect implements Serializable{
    public int width;
    public int length;
    public Rect(int w,int l){
        width = w;
        length = l;
    }
    public int area(){
        return width * length;
    }
}

8 控制台的输入输出

标准输入输出流

  • System.in :标准输入流
  • System.out:标准输出流
  • System.err:标准错误输出流
public class System_io_v1 {
    public static void main(String[] args) throws IOException {
        int a;
        a = System.in.read();
        System.out.println(a);
    }
}

c Rect(int w,int l){
width = w;
length = l;
}
public int area(){
return width * length;
}
}


## 8 控制台的输入输出

标准输入输出流

* System.in :标准输入流
* System.out:标准输出流
* System.err:标准错误输出流

```java
public class System_io_v1 {
    public static void main(String[] args) throws IOException {
        int a;
        a = System.in.read();
        System.out.println(a);
    }
}

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

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

相关文章

组件的概念

文章目录组件?从UI层面看组件化组件? 等下,你有没有留意到我说了一个很关键的词,叫组件。组件?直观的理解组件是一个什么东西?可拼接,可组合,搭积木,乐高积木? 对&…

Springboot定时任务调度的实现原理

前言 源码的世界是一片汪洋大海,springboot的源码更是如此,虽然用的时候似乎很简单,然而正是因为其内部的设计巧妙、复杂,才造就了其使用上的简单易上手。罗马不是一天建起来的,要完全理解它也并非一时的事&#xff0c…

webdriver的尝试:一 【webdriver自动打开浏览器与页面】

文章目录Webdriver尝试使用步骤1:安装类库2:安装驱动3:配置环境3:编写脚本4:执行脚本Webdriver 网站地址 Selenium webdriver 简单介绍:webdriver是一个api和协议。支持多种语言。主要功能,通…

大米新闻微信小程序和Springboot新闻管理系统项目源码

介绍 本项目分为大米news小程序端和springboot新闻管理系统后台项目。小程序主要用来新闻展示,后台管理系统用于提供相关新闻API。 项目源码 参考:https://www.bilibili.com/video/BV1TD4y1j7g3/?spm_id_from333.337.search-card.all.click&vd_s…

day08 常用API

1.API 1.1 API概述-帮助文档的使用 什么是API ​ API (Application Programming Interface) :应用程序编程接口 java中的API ​ 指的就是 JDK 中提供的各种功能的 Java类,这些类将底层的实现封装了起来,我们不需要关心这些类是如何实现的&a…

两个链表的第一个公共结点

今天为大家带来一道题目: 这个题目先来看看我自己写的错误版本 public class Solution {public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {ListNode tmp1pHead1;ListNode tmp2pHead2;while(pHead1!null&&pHead2!null){ListNode cur…

Axure8.0动态面板使用

Axure动态面板是最常使用的,今天我们就来详细介绍一下。 动态面板是Axure中一个非常强大的高级元件,用于实现多个状态的切换展示,可以将其看成一个容器,可以容纳多种不同状态,通过各种交互触发其状态发生变化。 通过以…

年终盘点丨2022边缘计算大事记

2022年进入尾声了,每年到了年底,边缘计算社区都会盘点过去一年边缘计算领域发生的值得您关注的事情。今年的边缘计算领域发生很多不一样的精彩:加强面向特定场景的边缘计算能力刷屏一整年,安波福43亿美元收购风河,全球…

C++图论 最短路问题总结

目录 最短路问题 图的存储 一、单源最短路 ① 朴素Dijkstra O(n^2) 练习题 代码 ② 堆优化Dijkstra O(mlogn) 练习题 代码 ③ Bellman_ford O(nm) 练习题 代码 ④ Spfa O(n) - O(nm) 练习题 ​代码 二、多源最短路 Floyd O(n^3) 练习题 代码 最短路问题 图…

C# 数据库访问方法

一 访问数据的两种基本方式 1 方式1:DataAdapter及DataSet ① 适合于“离线”处理; ② 自动建立Command对象; 方式2:DataReader ① 适合于只读数据,效率较高 它们都要使用Connection及Command 二 Connection对象…

Android解析服务器响应数据

文章目录Android解析服务器响应数据解析XML格式数据Pull解析方式SAX解析方式解析JSON数据使用JSONObject使用GSON的方式来解析JSON数据Android解析服务器响应数据 解析XML格式数据 通常情况下,每一个需要访问网络的应用程序都会有一个自己的服务器,我们可以向服务器提交自己的…

多线程——概念及线程安全

文章目录多线程概念进程vs线程多线程的优势/好处/使用场景线程的状态创建线程的方式线程的启动Thread中,start()和run()有什么区别?Thread类中的常用方法join()获取当前线程引用线程休眠线程中断线程的属性多线程效率局部变量在多线程中的使用线程安全问题1.什么情况会产生线程…

replit搭建

本文章用于快速搭建“出去”的节点,很简单 每个月只有100G流量中间可能会停止运行,需要手动进入项目开启 1、需要注册一个Replit账号 点击注册 支持Github登录,其他登录也行 2、使用这个模板项目 随便起个名字 3、运行 进行完第二步&am…

【开源项目】第三方登录框架JustAuth入门使用和源码分析

第三方登录框架JustAuth入门使用和源码分析 项目介绍 JustAuth,如你所见,它仅仅是一个第三方授权登录的工具类库,它可以让我们脱离繁琐的第三方登录 SDK,让登录变得So easy! JustAuth 集成了诸如:Github、Gitee、支付…

九、kubernetes中Namespace详解、实例

1、概述 Namespace是kubernetes系统中的一种非常重要资源,它的主要作用是用来实现多套环境的资源隔离或者多租户的资源隔离。 默认情况下,kubernetes集群中的所有的Pod都是可以相互访问的。但是在实际中,可能不想让两个Pod之间进行互相的访…

花费数小时,带你学透Java数组,这些常用方法你还记得吗?

推荐学习专栏:Java 编程进阶之路【从入门到精通】 文章目录1. 数组2. 一维数组2.1 声明2.2 初始化2.3 使用3. 二维数组3.1 声明3.2 初始化3.3 使用4. 数组在内存中的分布5. 数组常用的方法5.1 Arrays.toString方法5.2 Arrays.copyOf方法5.3 Arrays.copyOfRange方法5…

麦克斯韦(Maxwell)方程组的由来

美国著名物理学家理查德费曼(Richard Feynman)曾预言:“人类历史从长远看,好比说到一万年以后看回来,19世纪最举足轻重的毫无疑问就是麦克斯韦发现了电动力学定律。” 这个预言或许对吧。可是费曼也知道,麦…

疫情三年划上终止符,好易点却把个人健康写入了产品基因

作者 | 牧之 编辑 | 小沐 出品 | 智哪儿 zhinaer.cn随着12月26日国家卫健委发布的一纸公告,新冠肺炎正式更名为新冠感染。而从次年1月8日起,新冠将被实施「乙类乙管」。同时出入境也将采取开放性政策。这意味着,持续三年的「疫情时期」&#…

大数据技术——HBase简介

文章目录1. HBase定义2. HBase数据模型2.1 逻辑存储结构2.2 HBase 物理存储结构3. HBase基础架构1. HBase定义 HBase – Hadoop Database,是一个高可靠性、高性能、面向列、可伸缩的分布式存储系统,利用HBase技术可在廉价PC Server上搭建起大规模结构化存…

基于BP神经网络的电力负荷预测(Matlab代码实现)

💥💥💥💞💞💞欢迎来到本博客❤️❤️❤️💥💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑…