JAVA学习笔记31(IO流)

news2024/10/1 12:22:32

1.IO流

1.文件流

​ *文件在程序中是以流的形式来操作的

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

2.常用文件操作

1.创建文件对象

1.new File(String pathname)

//根据路径构建一个File对象

main()
{
	
}

public void create01() {
    String filePath = "e:\\news1.txt";
    File filePath = new File(filePath);
    
    try{
    	file.createNewFile();     
    } catch (IOException e){
        e.printStackTrace();
    }

}

2.new File(File ,String child)

//根据父目录文件+子路径构建

public void create02() {
	File parentFile = new File("e:\\");
    String fileName = "new2.txt";
    //这里的file对象,在java程序中,只是一个对象
    //只有执行了createNewFile方法,才会真正的创建文件
    File file = new File(parentFile,fileName)
        
    try{
    	file.createNewFile();     
    } catch (IOException e){
        e.printStackTrace();
    }
}

3.new File(String parent , String child)

//根据父目录+子路径构建

public void create03() {
    String parentPath = "e:\\";	//“\\”表示转义字符“\”
    String fileName = "news3.txt";
    File file = new File(parentPath, fileName);
    
    try{
    	file.createNewFile();     
    } catch (IOException e){
        e.printStackTrace();
    }
}

​ *createNewFile 创建新文件

2.获取文件信息

public class test01 {
	public static void main(String[] args) {
 		       
    }
    //获取文件信息
    public void info() {
		//先创建文件对象
        File file = new File("e:\\news1.txt");
        
        //调用相应的方法,得到对应信息
    	System.out.println("文件名字=" + file.getName());
    	//getName、getAbsolutePath、length、exists、isFile、isDirectory
        System.out.println("文件绝对路径=" + file.getAbsolutePath());
        System.out.println("文件父级目录=" + file.getParent());
        System.out.println("文件大小(字节)=" + file.length());
        System.out.println("文件是否存在=" + file.exists());//T
        System.out.println("是不是一个文件=" + file.isFile());//T
        System.out.println("是不是一个目录=" + file.isDirectory());//T
}

3.目录的操作和文件删除

​ *mkdir创建一级目录、mkdirs创建多级目录、delete删除空目录或文件

//判断d:\\news1.txt是否存在,如果存在就删除
@Test
public void m1() {
    String filePath = "d:\\news1.txt";
    File file = new File(filePath);
    if(file.exists()) {
        file.delete()
    } else {
        System.out.println("该文件不存在...")}
}

//判断目录D:\\demo02是否存在,如果存在就删除,否则提示不存在
//在java中,目录也被当做文件
@Test
public void m2() {
    String filePath = "D:\\demo02";
    File file = new File(filePath);
    if(file.exists()) {
        file.delete()
    } else {
        System.out.println("该文件不存在...")}
}

//判断目录D:\\demo\\a\\b\\c 是否存在,如果存在就提示存在,否则就创建
//在java中,目录也被当做文件
@Test
public void m3() {
    String directoryPath = "D:\\demo\\a\\b\\c";
    File file = new File(directoryPath);
    if(file.exists()) {
        System.out.println("该文件存在")} else {
        //创建多级目录,返回boolean值
        if(file.mkdirs()) {
            System.out.println(directoryPath + "创建成功");
        }
    }
}

3.IO流原理及流的分类

1.I/O是Input/Output的缩写,I/O技术用于处理数据传输,读/写文件,网络通讯

2.Java中,对于数据的输入/输出操作以“流(stream)”的方式进行

3.java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据

4.输入input:读取外部数据(磁盘,光盘等存储设备的数据)到程序(内存)中

5.输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中

在这里插入图片描述

1.流的分类

1.输入流和输出流

1.按操作数据单位不同分为:字节流(8bit)【二进制文件】,字符流(按字符)【文本文件】

2.按数据流额流向不同分为:输入流,输出流

3.按流的角色的不同分为:节点流,处理流/包装流

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

1.InputStream

:字节输入流

​ *InputStream抽象类是所有类字节输入流的超类

​ *常用子类

1.FileInputStream:文件输入流

@Test
//单个字节读取,效率低
public void readFile01() {
    String filePath = "e:\\hello.txt";
    int readData = 0;
     FileInputStream fileInputStream = null
    try {
        //创建FileInputStream对象,用于读取文件
        fileInputStream = new FileInputStream(filePath);
        //从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
        //如果返回-1,表示读取完毕
        while((readData = fileInputStream.read())!= -1) {
            System.out.print((char)readData);//转成char显示
        }
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        //关闭文件流,释放资源
    	fileInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//使用read(byte[] b)读取文件,提高效率
@Test
public void readFile02() {
    String filePath = "e:\\hello.txt";
    int readData = 0;
    //字节数组
    byte[] buf = new byte[8];//一次读取8个字节
    int readLen = 0;
    
    
     FileInputStream fileInputStream = null
    try {
        //创建FileInputStream对象,用于读取文件
        fileInputStream = new FileInputStream(filePath);
        //从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
        //如果返回-1,表示读取完毕
        //如果读取正常,返回实际读取的字节数
        while((readLen = fileInputStream.read(buf))!= -1) {
            System.out.print(new String(buf,0,readLen);
        }
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        //关闭文件流,释放资源
    	fileInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2.BufferedInputStream:缓冲字节输入流

3.ObjectInputStream:对象字节输入流

2.OutputStream

​ *FileOutputStream

@Test
public void writeFile() {
    //创建FileOutputStream对象
    String filePath = "e:\\a.txt";
    FileOutputStream fileOutputStream = null;
    
    try {
        //1.new FileOutputStream(filePath)创建方式,当写入内容时,会覆盖原来的内容
        //2.new FileOutputStream(filePath , true)创建方式,当写入内容时,是追加到文件后面
        
        
        //得到FileOutputStream对象
        fileOutputStream = new FileOutputStream(filePath);
        //写入一个字节
        fileOutputStream.write('H');
        //写入字符串
        String str = "hello,world";
        //str.getBytes()可以把字符串->字节数组
        fileOutputStream.write(str.getBytes());
        //write(byte[] b ,int off,int len)将len字节从位于偏移量off的指定字节数组写入
        fileOutputStream.write(str.getBytes(), 0,str.length());
     	fileOutputStream.write(str.getBytes(), 0, 3);//只写入前3个字节
        
        
    } catch (IOException e) {
		e.printStackTrace();
    } finally {
        try {
			fileOutputStream.close()
        } catch (IOException e) {
        	e.printStackTrace();
        }
    }
}
3.FileReader和FileWriter介绍

​ *FileReader和FileWriter是字符流,即按照字符来操作io

​ *FileReader相关方法

1.new FileReader(File/String)

2.read:每次读取单个字符(汉字格式),返回该字符,如果到文件末尾返回-1

3.read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果文件末尾返回-1

​ *相关API

1.new String(char[]):将char[]转换为String

2.new String(char[], off, len):将char[]的指定部分转换成String

​ *FileWriter常用方法

1.new FileWriter(File/String):覆盖模式,相当于流的指针在首端

2.new FileWriter(File/String, true):追加模式,相当于流的指针在尾端

3.write(int):写入单个字符

4.write(char[]):写入指定数组的指定部分

5.write(char[], off ,len):写入指定数组的指定部分

6.write(String):写入整个字符串

7.write(String, off ,len):写入字符串的指定部分

​ *相关API

String类:toCharArray:将String转换成char[]

​ *注意

FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件

2.节点流和处理流

1.节点流可以从一个特定的数据源读写数据,如FileReader、FileWriter

在这里插入图片描述

2.处理流(也叫包装流)是“链接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,也更加灵活,如BufferedReader、BufferedWriter

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

1.BufferedReader

​ *只能处理字符,不能处理字节

main()
{
    String filePath = "文件路径";
    BufferedReader bufferedReader = new BufferedReader(new FileReader(filepath,true));
    
    int readLen =0;
    String line;
    while((line = fileReader.readLine())!=null)
    {
 		System.out.println(line);       
    }
    
    //关闭流
    bufferedReader.close();
}
2.BufferedWriter

​ *只能处理字符,不能处理字节

public class test01 {
	public static void main(String[] args) {
 		String filePath ="文件路径";
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
        bufferedWriter.write("Hello,韩顺平教育");
            bufferedWriter.newLine();//插入一个和系统相关的换行
    } 
    
    bufferedWriter.close();
}
3.BufferedInputStream
public class test01 {
	public static void main(String[] args) {
 		String srcFilePath = "文件路径";
        String destFilePath = "目标路径";
        
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        
        try {
            bis = new BufferedInputStream(new FileInputStream(srcFilePath));
            bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
            
            //循环读取文件,斌写入到destFilePath
            byte[] buff = new byte[2024];
            int readLen = 0;
            
            while ((readLen = bis.read(buff))!= -1) {
                bos.write(buff, 0 ,readLen);
            }
            
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
			//关闭
            try {
				if(bis != null) bis.close();
                if(bos != null) bos.close();
            } catch {
                
            }
        }
    }           
}
4.BufferedOutputStream
3.对象处理流
1.ObjectOutputStream
public class test01 {
	public static void main(String[] args) {
 		//创建流对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src\\data.dat"));
        //写入对象(序列化)
        oos.writeInt(100);
        oos.writeBoolean(true);
        oos.writeChar('a');
        oos.writeDouble(9.5);
        oos.writeUTF("呜呜");
        oos.writeObject(new Dog("阿迪王",10));//序列化对象
    
        //关闭
        oos.close()
    
    }           
}

//序列化对象需要继承Serializable接口
class Dog implements Serializable {
    
}
2.ObjectInputStream
public class test01 {
	public static void main(String[] args) {
 		String filePath = "e:\\data.dat";
        
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
        
        //读取反序列化的顺序需要和保存数据(序列化)的顺序一致
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        Obejct dog = ois.readObject();
        System.out.println("运行类型=" + dog.getClass());
        System.out.println("dog信息=" + dog);
        
        
        //如果要调用Dog方法,需要向下转型
        Dog dog2 = (Dog)dog;
        dog2.getName();
        
        ois.close();
    }           
}

Serializable接口
class Dog implements Serializable {
    
}
3.注意事项

在这里插入图片描述

4.标准输入输出流

在这里插入图片描述

1.System.in
2.System.out
5.转换流

*字节–>字符

在这里插入图片描述

*处理纯文本数据时,使用字符流效率更高,并且有效解决了中文问题

*可以在使用时指定编码格式(比如: utf-8, gbk ,gb2312, ISO8859-1等)

1.InputStreamReader

在这里插入图片描述

public class test01 {
	public static void main(String[] args) throws IOException {
 		String filePath = "文件路径";
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
        BufferedReader br = new BufferedReader(isr);
        
        String s = br.readLine();
        System.out.println(s);
        
        br.close()
    }           
}
2.OutputStreamWriter

在这里插入图片描述

//将字节流FileOutputStream包装成字符流OutputStreamWriter,对文件写入(gbk格式)

//1.创建对象
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\a.txt"), "gbk");//以gbk方式写入

//2.写入
osw.write("hello,哈阿萨德");
//关闭
osw.close();
6.打印流
1.PrintStream
public class test01 {
	public static void main(String[] args) {
 		PrintStream out = System.out;
        out.print("john,hello");
        //print底层调用的write,也可以直接调用write进行打印
        out.write("大萨达".getBytes());
        
        out.close();
        
        //修改打印流输出的位置
        System.setOut(new PrintStream("e:\\f1.txt"));
                out.print("john,hello");
    }           
}
2.PrintWriter
public class test01 {
	public static void main(String[] args) {
 		PrintWriter printWriter = new PrintWriter(System.out);
            PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
        printWriter.print("hi,你好");
        printWriter.close();
    }           
}

4.拷贝图片

@Test
public void copyPoto() {
	FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    String srcfilePath = "图片路径e:\\Kola.jpg";
    String destfilePath = "储存路径e:\\kola2.jpg";
    
    try {
        fileInputStream = new FileInputStream(srcfilePath);
        fileOutputStream = new FileOutputStream(destfilePath);
        //定义一个字节数组,提高读取效果
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = fileInputStream.read(buf)) != -1) {
            fileOutputStream.write(buf,0,readLen);//一定要用这个方法
        }
        System.out.println("拷贝OK")
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if(fileInputStream != null) {
             fileInputStream.close()   
            }
            if(fileOutputStream != null) {
				fileOutputStream.close();
            }
        } catch (IOException e) {
			e.printStackTrace();
        }
    }
}

​ *Buffered拷贝

public class test01 {
	public static void main(String[] args) {
 		String srcFilePath ="文件路径";
        String desFilePath = "拷贝路径";
        BufferedReader br = null;
        BufferedWriter bw = null;
        String line;
        try {
            br = new BufferedReader(new FileReader(srcFilePath));
            bw = new BufferedWriter(new FileWriter(destFilePath));
            
            
            while((line = br.readLine()) != null) {
                bw.write(line);
                //readLine没有带换行符
                //插入换行符
                bw.newLine();
            }
        }
    }           
}

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

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

相关文章

人人都会给视频换脸_出色的AI换脸软件离线版你可以把视频换上明星脸

网盘下载 简单几步骤: 1、找个人脸照片,正面高清 2、找个视频,最好是单人的视频,或者只有一个女的,这样可以按照条件换脸 3、点击开始,等待完成即可(显卡勾选显卡,显卡不行选择CPU)…

最新win11配置cuda以及cudnn补丁教程

1、首先使用指令 nvidia-smi 查看电脑支持的**最高cuda**版本,例如:本机 12.2 2、进入CUDA下载cuda安装包 https://developer.nvidia.com/cuda-toolkit-archive 2、点击上方绿色的链接,按照图中序号选择的即可,最后点击下载。 …

【MySQL 数据宝典】【磁盘结构】- 004 redolog 重做日志

一、背景介绍 持久性要求: 对于已提交的事务,即使系统发生崩溃,其对数据库的更改也不能丢失。问题: 在事务提交前将所有修改的页面刷新到磁盘浪费资源。随机IO导致刷新速度慢。 解决方案: 【数据副本】记录事务执行过…

中仕公考:广东省2024高校毕业生‘三支一扶‘开始报名

广东省2024高校毕业生三支一扶于今日4月22日正式开始报名,报名人员请于2024年4月22日9:00-4月26日17:00登录广东省高校毕业生“三支一扶”计划信息管理系统进行报名。

裤子什么面料适合夏季?必备的五条夏季男生裤子

许多男生朋友应该都发现,想选一条穿着舒服的裤子可真不容易,总是会出现各种情况,列如常见的卡档、显腿粗、显矮等等。甚至还会出现一些质量问题,导致各种闹心。 为了让大家可以找到更适合自己的裤子,我特别花了比较长…

HTML重要标签梳理学习

1、HTML文件的框架 使用VS Code编码时&#xff0c;输入!选中第一个&#xff01;就可以快速生成一个HTML文件框架。 2、标签 <hr> <!--下划线--> <br> <!--换行--> <strong>加粗</strong> &…

ChatGPT4.5:能力大提升,全新体验

说明 ChatGPT4是2023年的5月份发布的&#xff0c;马上就发布一周年了。其他的大语言模型&#xff0c;比如Claude和开源的Lama也相继更新了最新版本。而根据目前国外发布的各种消息来看&#xff0c;ChatGPT4.5也即将发布。 GPT-4.5 Turbo 发布时间 最新消息显示&#xff0c;Op…

Meta 发布 Llama 3:迄今为止最强大的开源大语言模型

Meta 发布了 Llama 3&#xff0c;其中包含 8B 和 70B 两个版本。Llama 3 以强大的性能和丰富的功能成为迄今为止最强大的开源大语言模型之一。从已经释放的信息来看&#xff0c;Llama 3 在模型架构、训练数据、训练规模和指令微调等方面进行了多项改进&#xff0c;使其在推理、…

详解Java中的五种IO模型

文章目录 前言1、内核空间和用户空间2、用户态和内核态3、上下文切换4、虚拟内存5、DMA技术6、传统 IO 的执行流程 一、阻塞IO模型二、非阻塞IO模型三、IO多路复用模型1、IO多路复用之select2、IO多路复用之epoll3、总结select、poll、epoll的区别 四、IO模型之信号驱动模型五、…

Git 原理及使用 (带动图演示)

文章目录 &#x1f308; Ⅰ Git 安装&#x1f319; 01. Linux - centos &#x1f308; Ⅱ Git 工作区、暂存区和版本库&#x1f319; 01. 认识工作区、暂存区和版本库&#x1f319; 02. 使用 Git 管理工作区的文件 &#x1f308; Ⅲ Git 基本操作&#x1f319; 01. 创建本地仓库…

Java代码基础算法练习-斐波纳契数列-2024.04.22

任务描述&#xff1a; 1&#xff0c;1&#xff0c;2&#xff0c;3&#xff0c;5&#xff0c;8&#xff0c;13&#xff0c;21&#xff0c;34&#xff0c;55&#xff0c;89……这个数列则称为“斐波那契数列”&#xff0c;其中每 个数字都是“斐波那契数”。 输入一个整数N(N不大…

服务器渲染技术(JSPELJSTL)

目录 前言 一.JSP 1.基本介绍 3.page指令(常用) 4.JSP三种常用脚本 4.1 声明脚本 <%! code %> 4.2 表达式脚本 <% code %> 4.3 代码脚本 <% code %> 4.4 注释 <%-- 注释 --%> 5. JSP 内置对象 5.1 基本介绍 5.2 九个内置对象 6.JSP域对象 二…

4-内核开发-第一个块设备模块开发案例

4-内核开发-第一个块设备模块开发案例 目录 4-内核开发-第一个块设备模块开发案例 1.开发原则创建步骤 2. 编译并加载模块 ​3.安装模块 4.检查模块是否加载成功 5.通过设备名称查看 6. 创建一个块设备文件 7. 查看块设备 8.模块卸载 9.总结 课程简介&#xff1a; L…

Qt-饼图示范

1.效果图 2.代码如下 2.1 .h文件 #ifndef PIECHARTWIDGET_H #define PIECHARTWIDGET_H#include <QWidget> #include <QChartView> #include <QPieSeries>#include<QVBoxLayout> #include<QMessageBox> #include <QtCharts>struct PieDat…

电子印章盖骑缝章

电子印章盖骑缝章是指在电子文档&#xff08;如PDF文件&#xff09;中&#xff0c;使用电子印章技术&#xff0c;为文档添加一个跨越多页、连续显示的电子印章图像&#xff0c;以模拟传统纸质文档上的骑缝章效果。以下是实现电子印章盖骑缝章的步骤&#xff1a; 一. 准备电子印…

linux休眠唤醒流程,及示例分析

休眠流程 应用层通过echo mem > /sys/power/state写入休眠状态&#xff0c;给一张大概流程图 这个操作对应在kernel/power/main.c的state这个attr的store操作 static ssize_t state_store(struct kobject *kobj, struct kobj_attribute *attr,const char *buf, size_t n) …

Linux - Docker 安装 Nacos

拉取 Nacos 镜像 使用以下命令从 Docker Hub 拉取最新版本的 Nacos 镜像&#xff1a; docker pull nacos/nacos-server启动 Nacos 容器 使用以下命令启动 Nacos 容器&#xff1a; docker run -d \--name nacos \--privileged \--cgroupns host \--env JVM_XMX256m \--env M…

【Harmony3.1/4.0】笔记三

概念 网格布局是由“行”和“列”分割的单元格所组成&#xff0c;通过指定“项目”所在的单元格做出各种各样的布局。网格布局具有较强的页面均分能力&#xff0c;子组件占比控制能力&#xff0c;是一种重要自适应布局&#xff0c;其使用场景有九宫格图片展示、日历、计算器等…

Vue2 —— 学习(十)

一、vue-resource 库 了解即可 在之前的 vue 版本中经常使用 这个库发送 ajax 请求 现在建议使用 axios 我们可以通过使用 vue-resource 库 来实现发送 ajax 请求 它是 vue 的一个插件库 Vue.use() 就能使用我们的插件了 我们引入后去 我们的实例对象 vc 中查看 发现出现…

设计模式之访问者模式(下)

3&#xff09;访问者模式与组合模式联用 1.概述 在访问者模式中&#xff0c;包含一个用于存储元素对象集合的对象结构&#xff0c;可以使用迭代器来遍历对象结构&#xff0c;同时具体元素之间可以存在整体与部分关系&#xff0c;有些元素作为容器对象&#xff0c;有些元素作为…