Java IO流(详解)

目录

1.概述

2.File文件类

2.1 文件的创建操作

2.2 文件的查找操作

3. File里面一些其他方法

3.1 经典案例

4. IO流

4.1 概念

4.2 IO分类

4.3 字节输出流

4.4 字节输入流

4.5 案例

4.6 字符输出流

4.7 字符输入流

4.8 案例

4.9 处理流--缓冲流

4.10 对象流:


1.概述

在学习io流之前,我们需要先学习File文件类。因为它只能对文件进行操作,但是无法对文件中的内容进行操作

2.File文件类

在java jdk关于对文件(目录和文件)的操作都封装到File类。该类中包含了文件的各种属性以及操作方法。该类放在jdk-java.io包下。

2.1 文件的创建操作

 public static void main(String[] args) throws IOException {
//        //创建一个文件对象--参数文件的路径--绝对路径和相对路径
//        File file=new File("D:\\qy174.txt");
//        //相对路径--当前工程
//        File file02=new File("qy174.txt");
//        //调用创建功能--文件
//        file.createNewFile();
//        file02.createNewFile();

//        File file=new File("D://gyh//zql//ldh");
//        //创建目录
//        //file.mkdir();
//        //创建多级目录 /a/b/c/d
//        file.mkdirs();

        //删除文件或目录
//        File file02=new File("D:\\aaaaaaa");
//        //删除目录时只能删除空目录
//        file02.delete();

        //修改文件名称
        File file02=new File("qy174.txt");
        File file01=new File("zhenshuai.txt");
        file02.renameTo(file01);
    }

2.2 文件的查找操作

public class Test02 {
    public static void main(String[] args) {
        File file01=new File("D:\\aaaaaaa");
//        File file01=new File("zhenshuai.txt");
        //获取文件名
        String name = file01.getName();
        System.out.println("文件名:"+name);
        //获取文件的父路径
        String parent = file01.getParent();
        System.out.println("父路径:"+parent);
        //获取文件相对路径
        String path = file01.getPath();
        System.out.println("文件路径:"+path);
        //绝对路径
        String absolutePath = file01.getAbsolutePath();
        System.out.println(absolutePath);
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        //获取该目录下所有的子文件名
        String[] list = file01.list();
        for(String s:list){
            System.out.println(s);
        }
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        //获取当前目录下的所有子文件对象
        File[] files = file01.listFiles();
        for(File f:files){
            String absolutePath1 = f.getAbsolutePath();
            System.out.println(absolutePath1);
        }
    }
}

3. File里面一些其他方法

//判断文件或目录是否存在。
        boolean exists = file01.exists();
        System.out.println("文件是否存在"+exists);
        //判断文件是否为目录
        boolean directory = file01.isDirectory();
        System.out.println("该文件是否为目录:"+directory);

3.1 经典案例

查询某个目录下所有的文件。

public static void main(String[] args) {
        File file=new File("D:\\gz01-spring-transaction01");
        listFile(file);
    }
    public static void listFile(File file){
        //判断file是否为目录
        boolean directory = file.isDirectory();
        if(directory){
            //查看该目录下所有的文件对象
            File[] files = file.listFiles();
            //遍历
            for (File f:files){
                //递归调用
                listFile(f);
            }
        }else{
            System.out.println("文件名:"+file.getAbsolutePath());
        }
    }

4. IO流

4.1 概念

上面讲解得到File,它只能对文件进行操作,但是无法对文件中的内容进行操作。如果需要对文件中的内容进行操作则需要IO流。IO针对文件的内容操作的一个类集合

4.2 IO分类

流的方向: 输入流和输出流。

 根据流的内容: 字节流和字符流。

4.3 字节输出流

字节输出流的父类:OutputStream,它是所有字节输出流的父类,它是一个抽象类,最常见的子类FileOutputStream。

public static void main(String[] args) {
        //创建一个字节输出流--往zhenshuai.txt文件中输出内容---该流默认覆盖原本的内容
        OutputStream os = null;
        try {
            os = new FileOutputStream(new File("src/zhenshuai.txt"), true);
            String msg = "曹荣华也很真帅";
            //调用输出功能---必须为字节类型--转化为字节
            os.write(msg.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

4.4 字节输入流

以字节的方式读取文件中的内容。读取到程序中【内存中】。 字节输入流的父类InputStream,它里面包含操作字节的方法, 它也是一个抽象类,最常见的子类:FileInputStream。

public class Test02 {
    public static void main(String[] args) throws Exception {
        //创建一个字节输入流对象
        InputStream is=new FileInputStream(new File("src/zhenshuai.txt"));
        //调用读取的方法--每次读取一个字节--并把读取的内容返回--如果没有内容返回-1
        int a=-1;
        while ((a=is.read())!=-1){
            char c= (char) a;
            System.out.print(c);
        }
        is.close();
    }
}

4.5 案例

通过流完成文件的复制。

public class Test03 {
    public static void main(String[] args) throws Exception {
        //输入流
        InputStream is=new FileInputStream(new File("D:\\rabbitmq视频\\1.什么是mq.mp4"));
        //输出流
        OutputStream os=new FileOutputStream(new File("D:\\qy174.mp4"));
        int a=-1;
        while((a=is.read())!=-1){
             os.write(a);
        }
        is.close();
        os.close();
    }
}

4.6 字符输出流

Write类,它是所有字符输出流的父类,输出的内容以字符为单位。它下面常用的子类FileWrite。

public class Test04 {
    public static void main(String[] args) throws Exception {
        //创建一个字符输出流--如果文件不存在--该流回自动创建
        Writer w=new FileWriter(new File("liurui.txt"),true);
        String str="你好李焕英! 热辣滚烫";
        w.write(str);
        w.close();
    }
}

4.7 字符输入流

Reader它是字符输入流的一个父类,它也是抽象类,常见的子类FileReader.以字符为单位。

public class Test05 {
    public static void main(String[] args) throws Exception {
        Reader r=new FileReader(new File("liurui.txt"));
        //读取的单位为一个字符--如果没有内容返回的结果-1
        int i=-1;
        while ((i=r.read())!=-1){
            char c= (char) i;
            System.out.print(c);
        }
        r.close();

    }
}

4.8 案例

字符流它只能复制文本内容---无法复制文本之外的内容:比如视频,音频,图片 word。

public class Test06 {
    public static void main(String[] args) throws Exception{
        //输入流
        Reader r=new FileReader(new File("D:\\2.jpg"));
        //输出流
        Writer w=new FileWriter(new File("D:\\3.jpg"));

        int a=-1;
        while ((a=r.read())!=-1){
            w.write(a);
        }
        r.close();
        w.close();

    }
}

 字节流--可以操作任何文件的内容 字符流只适合操作文本的内容。

4.9 处理流--缓冲流

常用的缓冲流: BufferedInputStream 和BufferOutputStream 缓冲流是作用在流上。

public class Test07 {
    public static void main(String[] args)throws Exception {
        InputStream is=new FileInputStream(new File("liurui.txt"));
        //创建一个缓冲字节输入流
        BufferedInputStream bis=new BufferedInputStream(is);
        //缓冲流里面的方法操作文件内容
        int read =-1;
        while ((read=bis.read())!=-1){
            char c= (char) read;
            System.out.print(c);
        }
        bis.close();
        is.close();
    }
}
public class Test08 {
    public static void main(String[] args) throws Exception{
        OutputStream os=new FileOutputStream(new File("liurui.txt"));
        BufferedOutputStream bos=new BufferedOutputStream(os);
        String msg="hello";
        bos.write(msg.getBytes());

        bos.close();//刷新缓冲区
        os.close();
    }
}

提供效率:

public class Test09 {
    public static void main(String[] args) throws Exception {
        //开始时间
        long l = System.currentTimeMillis();
        //输入流
        InputStream is=new FileInputStream(new File("D:\\rabbitmq视频\\1.什么是mq.mp4"));
        BufferedInputStream bis=new BufferedInputStream(is);
        //输出流
        OutputStream os=new FileOutputStream(new File("D:\\qy174-02.mp4"));
        BufferedOutputStream bos=new BufferedOutputStream(os);
        int a=-1;
        while((a=bis.read())!=-1){
             bos.write(a);
        }
        bos.close();
        bis.close();
        is.close();
        os.close();
        //结束时间
        long l1 = System.currentTimeMillis();
        System.out.println("耗时:"+(l1-l));
    }
}

4.10 对象流:

操作java类对象。把java类对象写入到文件中,或者从文件中读取写入的java对象。

序列化: 把内存中的java对象写入到文件中的过程--序列化。

反序列化: 把文件中的对象读取到内存中---反序列化。

ObjectInputStream和ObjectOutputStream

ObjectOutputStream

把java对象写入到文件中。

public class Test10 {
    public static void main(String[] args) throws Exception{

        read();
    }
    public static void read() throws Exception{
        InputStream is=new FileInputStream(new File("liurui.txt"));
        ObjectInputStream ois=new ObjectInputStream(is);

        Object o = ois.readObject();

        ois.close();
        is.close();

        System.out.println(o);

    }
    //序列化过程: 借助ObjectOutputStream流 调用writeObject()  注意: 该类必须实现序列化接口Serializable
    public static void write() throws Exception{
        //把该对象写入liurui.txt文件中
        Student s=new Student(16,"闫克起");
        OutputStream os=new FileOutputStream(new File("liurui.txt"));
        ObjectOutputStream oos=new ObjectOutputStream(os);
        //把一个java对象写入文件时要求该对象所在的类必须实现序列化接口
        oos.writeObject(s);
        oos.close();
        os.close();

    }
}
class Student implements Serializable {
    private Integer age;
    private String name;

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Student(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    public Student() {
    }
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

IP地址定位与智慧城市和智能交通

智慧城市和智能交通是现代城市发展的关键领域,通过先进技术提升城市管理和居民生活质量。IP地址定位在交通监控、智能路灯管理等方面发挥了重要作用,本文将深入探讨其技术实现及应用。 交通监控与优化 通过IP地址连接交通传感器和摄像头,可…

useState函数

seState是一个react Hook(函数),它允许我们像组件添加一个状态变量,从而控制影响组件的渲染结果 数据驱动试图 本质:和普通JS变量不同的是,状态变量一旦发生变化组件的视图UI也会随着变化(数据驱动试图) 使用 修改状态 注意&am…

H5 Svg 半圆圆环占比图

效果图 主逻辑 /* 虚线长度 */ stroke-dasharray /* 偏移 */ stroke-dashoffset 代码 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge&qu…

基于jeecgboot-vue3的Flowable流程支持bpmn流程设计器与仿钉钉流程设计器-编辑多版本处理

因为这个项目license问题无法开源&#xff0c;更多技术支持与服务请加入我的知识星球。 1、前端编辑带有仿钉钉流程的处理 /** 编辑流程设计弹窗页面 */const handleLoadXml (row) > {console.log("handleLoadXml row",row)const params {flowKey: row.key,ver…

React@16.x(60)Redux@4.x(9)- 实现 applyMiddleware

目录 1&#xff0c;applyMiddleware 原理2&#xff0c;实现2.1&#xff0c;applyMiddleware2.1.1&#xff0c;compose 方法2.1.2&#xff0c;applyMiddleware 2.2&#xff0c;修改 createStore 接上篇文章&#xff1a;Redux中间件介绍。 1&#xff0c;applyMiddleware 原理 R…

数据融合工具(10)线重叠检查修复

一、需求背景 先明确一下“线重叠”的定义。 ArcGIS拓扑工具集中的拓扑规则&#xff1a; 不能自重叠&#xff08;线&#xff09; —线要素不得与自身重叠。这些线要素可以交叉或接触但不得有重合的线段。此规则适用于街道等线段可能接触闭合线的要素&#xff0c;但同一街道不得…

深入探讨极限编程(XP):技术实践与频繁发布的艺术

目录 前言1. 极限编程的核心原则1.1 沟通1.2 简单1.3 反馈1.4 勇气1.5 尊重 2. 关键实践2.1 结对编程2.1.1 提高代码质量2.1.2 促进知识共享2.1.3 增强团队协作 2.2 测试驱动开发&#xff08;TDD&#xff09;2.2.1 提升代码可靠性2.2.2 提高代码可维护性2.2.3 鼓励良好设计 2.3…

判断点与圆的位置关系(c++)

可以通过创建两个类来解决问题 &#xff1a; 代码&#xff1a; #include<iostream> using namespace std;class Point { public:void setX(int x){m_X x;}int getX(){return m_X;}void setY(int y){m_Y y;}int getY(){return m_Y;}private:int m_X;int m_Y;};class C…

【系统架构设计师】十一、系统架构设计(中间件|典型应用架构)

目录 九、中间件 9.1 基础概念 9.2 中间件分类 十、典型应用架构 10.1 J2EE和四层结构 10.2 JSPServletJavaBeanDAO 10.3 .NET和J2EE之争 往期推荐 历年真题练习 九、中间件 之前总提到中间件&#xff0c;那么中间件到底是什么&#xff1f;在系统架构中又扮演者什么角…

Spring与设计模式实战之策略模式

Spring与设计模式实战之策略模式 引言 在现代软件开发中&#xff0c;设计模式是解决常见设计问题的有效工具。它们提供了经过验证的解决方案&#xff0c;帮助开发人员构建灵活、可扩展和可维护的系统。本文将探讨策略模式在Spring框架中的应用&#xff0c;并通过实际例子展示…

C++ | Leetcode C++题解之第240题搜索二维矩阵II

题目&#xff1a; 题解&#xff1a; class Solution { public:bool searchMatrix(vector<vector<int>>& matrix, int target) {int m matrix.size(), n matrix[0].size();int x 0, y n - 1;while (x < m && y > 0) {if (matrix[x][y] targ…

LabVIEW异步和同步通信详细分析及比较

1. 基本原理 异步通信&#xff1a; 原理&#xff1a;异步通信&#xff08;Asynchronous Communication&#xff09;是一种数据传输方式&#xff0c;其中数据发送和接收操作在独立的时间进行&#xff0c;不需要在特定时刻对齐。发送方在任何时刻可以发送数据&#xff0c;而接收…

AI自动生成PPT哪个软件好?高效制作PPT优选这4个

7.15初伏的到来&#xff0c;也宣告三伏天的酷热正式拉开序幕~在这个传统的节气里&#xff0c;人们以各种方式避暑纳凉&#xff0c;享受夏日的悠闲时光。 而除了传统的避暑活动&#xff0c;我们还可以用一种新颖的方式记录和分享这份夏日的清凉——那就是通过PPT的方式将这一传…

【Linux】权限管理与相关指令

文章目录 1.权限、文件权限、用户文件权限的理解以及对应八进制数值表示、设置目录为粘滞位文件类型 2.权限相关的常用指令susudochmodchownchgrpumaskwhoamifile 1.权限、文件权限、用户 通过一定条件&#xff0c;拦住一部分人&#xff0c;给另一部分权利来访问资源&#xff0…

Amazon EC2 部署Ollama + webUI

最近和同事闲聊&#xff0c;我们能不能内网自己部署一个LLM&#xff0c;于是便有了Ollama webUI的尝试 对于Linux&#xff0c;使用一行命令即可 curl -fsSL https://ollama.com/install.sh | shollama --help Large language model runnerUsage:ollam…

【Dison夏令营 Day 21】用Python编写绘图

绘画 - 在屏幕上绘制线条和形状。单击标记形状的起点&#xff0c;再次单击标记形状的终点。可使用键盘选择不同的形状和颜色。 """Paint, for drawing shapes.Exercises1. Add a color. 2. Complete circle. 3. Complete rectangle. 4. Complete triangle. 5. A…

大厂面试官问我:为什么Redis的rehash采用渐进式,而Java的hashmap是一次性rehash?【后端八股文十二:Redis hash八股文合集】

本文为【Redis hash八股文合集】初版&#xff0c;后续还会进行优化更新&#xff0c;欢迎大家关注交流~ hello hello~ &#xff0c;这里是绝命Coding——老白~&#x1f496;&#x1f496; &#xff0c;欢迎大家点赞&#x1f973;&#x1f973;关注&#x1f4a5;&#x1f4a5;收藏…

PostgreSQL使用(二)

说明&#xff1a;本文介绍PostgreSQL的DML语言&#xff1b; 插入数据 -- 1.全字段插入&#xff0c;字段名可以省略 insert into tb_student values (1, 张三, 1990-01-01, 88.88);-- 2.部分字段插入&#xff0c;字段名必须写全 insert into tb_student (id, name) values (2,…

Windows 11几个常用的快捷键

WinQ/WinS&#xff1a;快速打开一键搜索 WinCtrlD&#xff1a;快速新建虚拟桌面。可以通过四根手指在触摸板划动进行切换&#xff0c;也可以通过WinTAB进行虚拟桌面切换 WinTAB&#xff1a;虚拟桌面切换 WinA&#xff1a;打开快速设置面板 WinD&#xff1a;快速切换到桌面&a…

springboot+vue+mybatis鲜花管理系统+PPT+论文+讲解+售后

随着科学技术的飞速发展&#xff0c;社会的方方面面、各行各业都在努力与现代的先进技术接轨&#xff0c;通过科技手段来提高自身的优势&#xff0c;鲜花管理系统当然也不能排除在外。鲜花管理系统是以实际运用为开发背景&#xff0c;运用软件工程开发方法&#xff0c;采用SSM技…