Java语法学习IO流

news2024/10/8 12:00:20

Java语法学习IO流

大纲

  1. 文件
  2. IO流

具体案例

1. 文件

基本介绍

在这里插入图片描述

创建文件

在这里插入图片描述
第一种:

 public static void main(String[] args) {
        String filePathName = "d:\\news1.txt";
        File file = new File(filePathName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

第二种:
相当于把第一种分开写

 public static void main(String[] args) {
        File parentfile = new File("d:\\");
        String fileName = "news2.txt";
        File file = new File(parentfile,fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

第三种:
与第二种差不多

public static void main(String[] args) {
        String parentName = "d:\\";
        String fileName = "news3.txt";
        File file = new File(parentName, fileName);
        try {
            file.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

获取文件相关信息

在这里插入图片描述

    	System.out.println(file.getName());
        //得到文件名字
        System.out.println(file.getAbsolutePath());
        //得到文件的绝对路径
        System.out.println(file.getParent());
        //得到父文件的名字
        System.out.println(file.length());
        //得到文件的字节大小
        file.exists();
        //判断文件是否存在
        file.isFile();
        //判断是不是一个文件
        file.isDirectory();
        //判断是不是一个目录

常用文件操作

在这里插入图片描述

2. IO流

IO流原理及其分类

原理:
在这里插入图片描述
在这里插入图片描述
分类:
在这里插入图片描述
字节流一般应用操作二进制文件,字符流操作文本文件

字节流

InputStream

在这里插入图片描述

FileInputStream

创建对象读取,使用read()

public static void readFile() {
        String filePath = "d:\\hello.txt";
        FileInputStream fileInputStream = null;
        int content = 0;
        try {
             fileInputStream = new FileInputStream(filePath);
             while ((content = fileInputStream.read()) != -1){
                 System.out.print((char) content);
             }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

使用read(byte [ ]),返回读取到的字节的个数
再转换为字符串

    public static void readFile() {
        String filePath = "d:\\hello.txt";
        FileInputStream fileInputStream = null;
        byte[] bytes = new byte[5];
        //创建一个字节的数组
        int readLength = 0;
        //设置读取到的字节长度
        try {
             fileInputStream = new FileInputStream(filePath);
             while ((readLength = fileInputStream.read(bytes) )!= -1){
                 //把读取到的字节个数存入readLength
                 System.out.print(new String(bytes,0,readLength));
                 //把字节转换为字符串,新建字符串,传入数组,和起始位置与长度
             }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fileInputStream.close();
                //关闭字节流,节省资源
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
BufferedInputStream

注意体现在包装上 ,具体方法查询API
创建方式,传入一个InputStream对象即可

BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(srcPath));
OutputStream
FileOutputStream

覆盖文本原来的内容,使用的如下构造器

fileOutputStream = new FileOutputStream(fileName);

如果想要把我们写的内容加到原来文本的末尾,这需要这种构造器

fileOutputStream = new FileOutputStream(fileName,true);

方法:
创建对象,使用write方法,如果这个路径没有这个文件,那么会自己先创建再添加

public static void writeFile(){
        String fileName = "d:\\hello.txt";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(fileName);
            fileOutputStream.write('H');
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

使用write(byte [ ])方法,把一个字符串转换为字节数组(可以利用String的getBytes)

 public static void writeFile(){
        String fileName = "d:\\hello.txt";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(fileName);
           String str = "hello,world";
            fileOutputStream.write(str.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

使用write(byte [ ] ,int off, int len)方法,传入一字节数组,指定开始的位置和长度

 fileOutputStream.write(str.getBytes(),2,5);
BufferedOutputStream

注意体现在包装上 ,具体方法查询API
创建方式,传入一个OutputStream对象即可

BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destPath));

文件拷贝

注意:
1.是一边读,一边写
2.注意使用 字节数组要考虑读取到字节的长度
采用节点流的方式

    public static void fileCopy(){
        String srcName = "D:\\java学习\\蛋糕.jpg";
        String destName = "D:\\java学习\\av.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        int readLength = 0;
        //存储读取字节数组的字节的多少
        byte[] bytes = new byte[1024];
        try {
            fileInputStream = new FileInputStream(srcName);
            fileOutputStream = new FileOutputStream(destName);
            while ((readLength = fileInputStream.read(bytes)) != -1){
                //把读取到的字节个数返回readLength,并把读到的字节存入字节数组
                fileOutputStream.write(bytes,0,readLength);
                //把字节数组里面读到的内容写入目的文件,注意这里的是读取到字节的个数,而不是数字的长度
            }
            System.out.println("读取结束");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //判断输入流,与输出流是否为空,并关闭
            try {
                if (fileInputStream != null){
                    fileInputStream.close();
                }
                if (fileOutputStream != null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

采用包装流动方式

public static void fileCopy() throws FileNotFoundException {
        String srcPath = "D:\\java学习\\蛋糕.jpg";
        String destPath = "D:\\java学习\\蛋糕2.jpg";
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            int readLength = 0;
            byte[] bytes = new byte[1024];
            bufferedInputStream = new BufferedInputStream(new FileInputStream(srcPath));
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destPath));
            while ((readLength = bufferedInputStream.read(bytes)) != -1){
                bufferedOutputStream.write(bytes,0,readLength);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (bufferedInputStream != null){
                    bufferedInputStream.close();
                }
                if (bufferedOutputStream != null){
                    bufferedOutputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

字符流

在这里插入图片描述
在这里插入图片描述

Reader
FileReader

与前面的FileInputStream使用方法相似
通过read方法

 public static void main(String[] args) throws IOException {
        String fileName = "d:\\hello.txt";
        FileReader fileReader = null;
        int date;
        fileReader = new FileReader(fileName);
        try {
            while ((date = fileReader.read()) != -1) {
                System.out.print((char) date);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            fileReader.close();
        }
    }

通过字符数组,和read方法

public static void main(String[] args) throws IOException {
        String fileName = "d:\\hello.txt";
        FileReader fileReader = null;
        int charLength;
        char[] chars = new char[3];
        fileReader = new FileReader(fileName);
        try {
            while ((charLength = fileReader.read(chars)) != -1){
                System.out.print(new String(chars,0,charLength));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            fileReader.close();
        }
    }
}
BufferedReader

具体见下面处理流

Writer
FileWriter

应用方式与前文的FileOutputStream差不多
覆盖文本原来的内容,使用的如下构造器

fileWriter = new FileWriter(fileName);

如果想要把我们写的内容加到原来文本的末尾,这需要这种构造器

fileWriter = new FileWriter(fileName,true);

下面是常见的写入的方法
write()
write(char [ ])
write(char [ ],int off, int len)
write(String)
write(String, int off, int len)

 fileWriter.write('H');
 fileWriter.write(chars);
 fileWriter.write(chars,1,3);
 fileWriter.write(str);
 fileWriter.write(str,6,4);
 fileWriter.write("只不过是些许风霜罢了".toCharArray(),6,4);

注意:写完之后要close或者flush该字符流,否则写不进去

BufferedWriter

具体见下面处理流

节点流和处理流

在这里插入图片描述
在这里插入图片描述

节点流:
是针对某一特殊的数据类型进行操作的,更为底层
处理流(包装流):
功能更加强大,把节点流封装进了包装流

BufferedReader

把所需要的节点流创建并传入包装流的构造器实现包装

String fileName = "d:\\hello.txt";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = bufferedReader.readLine()) != null ){
            System.out.println(line);
        }
        bufferedReader.close();      
BufferedWriter

对于是覆盖还是追加,是在传入字节流的时候创建的

String fileName = "d:\\hello.txt";
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileName, true));
        bufferedWriter.write("天下真是英杰无数");
        bufferedWriter.newLine();
        //这个语句相当于换行
        bufferedWriter.close();

对象流

序列化: 能够保证不仅保存了数据的值,还保存了其数据类型,这种我们称为序列化
**反序列化:**把我们保存的数据恢复他的数据类型和值
在这里插入图片描述
如果想要一个类可以实现序列化,就需要实现Serializable 或 Externalizable接口.
Serializable:这是一个标记接口,没有方法
Externalizable:这里面有方法,需要实现
在这里插入图片描述
对于第四点:
序列号对象时,static,transient修饰的成员不进行 序列化,反序列化后也得不到
对于第六点:
如果一个类实现了序列化的接口,而其里面又有其它类的对象,那么要求其它类也实现序列化的接口

ObjectOutputStream

在进行写入的时候,需要不同的write数据类型方法,写入不同的数据

public static void file() throws IOException {
        String filePath = "d:\\hello";
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
        objectOutputStream.write(100);
        objectOutputStream.writeBoolean(true);
        objectOutputStream.writeChar('a');
        objectOutputStream.writeDouble(2.2);
        objectOutputStream.writeLong(12);
        objectOutputStream.writeUTF("字符串");
        objectOutputStream.writeObject(new dog());
        objectOutputStream.close();
}
class dog implements Serializable{

}
ObjectInputStream

在读取的时候要对应的顺序读取,并且应该注意访问的权限,而且在进行序列化时,在哪个包哪个位置都有具体储存,所以如果有某个类的话,我们不能在其它地方新建一个一模一样的类,来读取

 public static void readFile() throws IOException, ClassNotFoundException {
        String filePath = "d:\\hello.txt";
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(filePath));
        System.out.println(objectInputStream.readInt());
        System.out.println(objectInputStream.readBoolean());
        System.out.println(objectInputStream.readChar());
        System.out.println(objectInputStream.readDouble());
        System.out.println(objectInputStream.readLong());
        System.out.println(objectInputStream.readUTF());
        System.out.println(objectInputStream.readObject());
        objectInputStream.close();
    }

标准输入输出流

在这里插入图片描述

转换流

因为我们在用字符流读取信息时不能设置读取到的编码格式,而使用字节流可以指定,于是我们可以在字节流指定编码后,转换成字符流
在这里插入图片描述
因为字符流的处理效率更高,所以先把字节流通过转换流转换,再用包装流接收

混在一起写

 String fileName = "d:\\hello.txt";
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "gbk"));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "gbk"));

分开写

String fileName = "d:\\hello.txt";
        InputStreamReader inread = new InputStreamReader(new FileInputStream(fileName),"gbk");
        BufferedReader br = new BufferedReader(inread);
        OutputStreamWriter outwrite = new OutputStreamWriter(new FileOutputStream(fileName), "gbk");
        BufferedWriter bw = new BufferedWriter(outwrite);

以上两种等价

打印流

只有输出流

PrintStream

打印字节流

public static void main(String[] args) throws IOException, ClassNotFoundException {
        PrintStream out = System.out;
        out.print("ad");
        out.write("as".getBytes());
        //也能正常调用字节流的方法
        System.setOut(new PrintStream("d:\\hello.txt"));
        //设置打印输出的地方
    }
PrintWriter
public static void main(String[] args) throws IOException, ClassNotFoundException {
        String fileName = "d:\\hello.txt";
        PrintWriter out = new PrintWriter(new FileOutputStream(fileName));
        out.print("ad");
        out.write("ss");
    }

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

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

相关文章

vulhub中Apache Druid 代码执行漏洞复现(CVE-2021-25646)

Apache Druid是一个开源的分布式数据存储。 Apache Druid包括执行嵌入在各种类型请求中的用户提供的JavaScript代码的能力。这个功能是为了在可信环境下使用,并且默认是禁用的。然而,在Druid 0.20.0及以前的版本中,攻击者可以通过发送一个恶…

2018 年全国职业院校技能大赛高职组“信息安全管理与评估”赛项任务书(笔记解析)

1. 网络拓扑图 2. IP 地址规划表 3. 设备初始化信息 阶段一 任务 1:网络平台搭建 1、根据网络拓扑图所示,按照 IP 地址参数表,对 WAF 的名称、各接口 IP 地址 进行配置。 2、根据网络拓扑图所示,按照 IP 地址参数表,对 DCRS 的名称、各接口 IP 地址 进行配置。 3、根据网…

C++项目 -- 高并发内存池(二)Thread Cache

C项目 – 高并发内存池(二)Thread Cache 文章目录 C项目 -- 高并发内存池(二)Thread Cache一、高并发内存池整体框架设计二、thread cache设计1.整体设计2.thread cache哈希桶映射规则3.TLS无锁访问4.thread cache代码 一、高并发…

CCF迎来新风采:揭晓2024-2026年度执行机构负责人名单!

会议之眼 快讯 中国计算机学会(CCF)成立于1962年,是一家全国性学会,拥有独立社团法人地位,同时是中国科学技术协会的会员单位。作为中国计算机及相关领域的学术团体,CCF的宗旨在于为该领域专业人士的学术和…

C

extern int a; //同一个项目声明 int r a > b ? a : b; 错误 scanf 不输入‘\n’,getchar()输入\n; printf()返回值 0次 system("cls"); 可以调用命令行函数 time(NULL)时间戳 srand((unsigned)time(NULL)); //随机数种子 int rev rand()%1001; //随…

Linux---yum命令详解

📙 作者简介 :RO-BERRY 📗 学习方向:致力于C、C、数据结构、TCP/IP、数据库等等一系列知识 📒 日后方向 : 偏向于CPP开发以及大数据方向,欢迎各位关注,谢谢各位的支持 目录 1.概念2.yum的配置信…

Open CASCADE学习|拓扑变换

目录 平移变换 旋转变换 组合变换 通用变换 平移变换 TopoDS_Shape out;gp_Trsf theTransformation;gp_Vec theVectorOfTranslation(0., 0.125 / 2, 0.);theTransformation.SetTranslation(theVectorOfTranslation);BRepBuilderAPI_Transform myBRepTransformation(out, th…

一篇文章了解区分指针数组,数组指针,函数指针,链表。

最近在学习指针,发现指针有这许多的知识,其中的奥妙还很多,需要学习的也很多,今天那我就将标题中的有关指针知识,即指针数组,数组指针,函数指针,给捋清楚这些知识点,区分…

【Linux取经路】进程控制——程序替换

文章目录 一、单进程版程序替换看现象二、程序替换的基本原理三、程序替换接口学习3.1 替换自己写的可执行程序3.2 第三个参数 envp 验证四、结语一、单进程版程序替换看现象 #include <stdio.h> #

【Funny guys】龙年专属测试鼠标寿命小游戏...... 用Python给大家半年了......

目录 【Funny guys】龙年专属测试鼠标寿命小游戏...... 用Python给大家半年了...... 龙年专属测试鼠标寿命小游戏用Python给大家半年了贪吃龙游戏 文章所属专区 码农新闻 欢迎各位编程大佬&#xff0c;技术达人&#xff0c;以及对编程充满热情的朋友们&#xff0c;来到我们的程…

Spring Boot + flowable 快速实现工作流

背景 使用flowable自带的flowable-ui制作流程图 使用springboot开发流程使用的接口完成流程的业务功能 文章来源&#xff1a;https://blog.csdn.net/zhan107876/article/details/120815560 一、flowable-ui部署运行 flowable-6.6.0 运行 官方demo 参考文档&#xff1a; htt…

SpringBoot整合Flowable最新教程(二)启动流程

介绍 文章主要从SpringBoot整合Flowable讲起&#xff0c;关于Flowable是什么&#xff1f;数据库表解读以及操作的Service请查看SpringBoot整合Flowable最新教程&#xff08;一&#xff09;&#xff1b;   其他说明&#xff1a;Springboot版本是2.6.13&#xff0c;java版本是1…

4. 树(二叉树、二叉查找树/二叉排序树/二叉搜索树、平衡二叉树、平衡二叉B树/红黑树)

树 1. 二叉树1.1 概述1.2 特点1.3 二叉树遍历方式1.3.1 前序遍历(先序遍历)1.3.2 中序遍历1.3.3 后序遍历1.3.4 层序遍历 2. 二叉查找树&#xff08;二叉排序树、二叉搜索树&#xff09;2.1 概述2.2 特点 3. 平衡二叉树3.1 概述3.2 特点3.3 旋转3.3.1 左旋3.3.2 右旋 3.4 平衡二…

指针的学习2

目录 数组名的理解 使用指针访问数组 一维数组传参的本质 冒泡排序 二级指针 指针数组 指针数组模拟二维数组 数组名的理解 数组名是数组首元素的地址 例外&#xff1a; sizeof(数组名),sizeof中单独放数组名&#xff0c;这里的数组名表示整个数组&#xff0c;计算的…

EasyCVR智能视频监控平台云台降低延迟小tips

TSINGSEE青犀视频监控汇聚平台EasyCVR可拓展性强、视频能力灵活、部署轻快&#xff0c;可支持的主流标准协议有国标GB28181、RTSP/Onvif、RTMP等&#xff0c;以及支持厂家私有协议与SDK接入&#xff0c;包括海康Ehome、海大宇等设备的SDK等。平台既具备传统安防视频监控的能力&…

彻底学会系列:一、机器学习之线性回归

1.基本概念 线性回归&#xff1a; 有监督学习的一种算法。主要关注多个因变量和一个目标变量之间的关系。 因变量&#xff1a; 影响目标变量的因素&#xff1a; X 1 , X 2 . . . X_1, X_2... X1​,X2​... &#xff0c;连续值或离散值。 目标变量&#xff1a; 需要预测的值: t…

智慧未来已至:人工智能与数字孪生共筑城市新纪元

随着科技的飞速发展&#xff0c;人工智能与数字孪生技术正逐步成为智慧城市建设的核心驱动力。 这两项技术的结合&#xff0c;不仅将彻底改变城市的传统面貌&#xff0c;更将引领我们走向一个更加高效、便捷、绿色的未来。 一、智慧城市的新内涵 智慧城市&#xff0c;是指在城…

DDoS攻击:分布式拒绝服务攻击的威胁与对策

DDoS攻击&#xff1a;分布式拒绝服务攻击的威胁与对策 随着互联网的快速发展&#xff0c;网络安全威胁也在不断增加。其中&#xff0c;分布式拒绝服务攻击&#xff08;DDoS&#xff09;是一种常见且具有破坏性的攻击方式&#xff0c;给个人用户、企业和组织的网络基础设施带来了…

爬虫工作量由小到大的思维转变---<第四十五章 Scrapyd 关于gerapy遇到问题>

前言: 本章主要是解决一些gerapy遇到的问题,会持续更新这篇! 正文: 问题1: 1400 - build.py - gerapy.server.core.build - 78 - build - error occurred (1, [E:\\项目文件名\\venv\\Scripts\\python.exe, setup.py, clean, -a, bdist_uberegg, -d, C:\\Users\\Administrat…

React进阶 - 15(React 中 ref 的使用)

本章内容 目录 一、e.target 获取事件对应“元素”的DOM节点二、ref三、ref 和 setState 合用 上一节我们了解了 React中的”虚拟DOM“中的”Diff算法““ &#xff0c;本节我们来说一说 React中 ref的使用 一、e.target 获取事件对应“元素”的DOM节点 打开之前工程中的 To…