IO流
IO:输入/输出
流:抽象概念,对数据传输的总称,流的本质是数据传输
即流向内存是输入流,流出内存的输出流。
IO流根据数据流向分:
- 输入流:读数据; 输出流:写数据
IO流根据数据类型分:
-
字节流:字节输入流,字节输出流 (以字节为单位,读写数据的流)
-
字符流:字符输入流,字符输出流(以字符为单位,读写数据的流)
一般来说,我们说IO流的分类是按照数据类型来分的
那么这两种流都在什么情况下使用呢?
- 如果数据通过Window自带的记事本软件打开,我们还可以读懂里面的内容,就使用字符流,
否则使用字节流。如果你不知道该使用哪种类型的流,就使用字节流
(由于字节流操作中文不是特别方便,所以java提供字符流)
字符流=字节流+编码表
顶级父类们
输入流 | 输出流 | |
---|---|---|
字节流 | 字节输入流 InputStream | 字节输出流 OutputStream |
字符流 | 字符输入流 Reader | 字符输出流 Writer |
读后感:字节流感觉比字符流写的费劲点,每次都要自己new byte[],目前还是多用字符流吧。效率什么的没有考虑过还。
2022.3.7
在从字节流转化为字符流时,实际上就是byte[]转化为String时,
public String(byte bytes[], String charsetName)
有一个关键的参数字符集编码,通常我们都省略了,那系统就用操作系统的lang而在字符流转化为字节流时,实际上是String转化为byte[]时,
byte[] String.getBytes(String charsetName)
也是一样的道理所有的文件在硬盘或在传输时都是以字节的方式进行的,包括图片等都是按字节的方式存储的,而字符是只有在内存中才会形成,所以在开发中,字节流使用较为广泛。
字符流处理的单元为2个字节的Unicode字符,分别操作字符、字符数组或字符串,而字节流处理单元为1个字节,操作字节和字节数组。所以字符流是由Java虚拟机将字节转化为2个字节的Unicode字符为单位的字符而成的,所以它对多国语言支持性比较好!如果是音频文件、图片、歌曲,就用字节流好点,如果是关系到中文(文本)的,用字符流好点. 所有文件的储存是都是字节(byte)的储存,在磁盘上保留的并不是文件的字符而是先把字符编码成字节,再储存这些字节到磁盘。在读取文件(特别是文本文件)时,也是一个字节一个字节地读取以形成字节序列. 1.字节流可用于任何类型的对象,包括二进制对象,而字符流只能处理字符或者字符串; 2. 字节流提供了处理任何类型的IO操作的功能,但它不能直接处理Unicode字符,而字符流就可以。 字节流与字符流主要的区别是他们的的处理方式
一、字节流
一切皆为字节
一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样如此。所以,字节流可以传输任意文件数据。在操作流的时候,我们要时刻明确,无论使用什么样的流对象,底层传输的始终为二进制数据。
OutputStream[字节输出流]
java.io.OutputStream
抽象类是表示字节输出流的所有类的超类,将指定的字节信息写出到目的地。它定义了字节输出流的基本共性功能方法。
public void close()
:关闭此输出流并释放与此流相关联的任何系统资源。public void flush()
:刷新此输出流并强制任何缓冲的输出字节被写出。public void write(byte[] b)
:将 b.length字节从指定的字节数组写入此输出流。public void write(byte[] b, int off, int len)
:从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流。public abstract void write(int b)
:将指定的字节输出流。
小贴士:
close方法,当完成流的操作时,必须调用此方法,释放系统资源。
FileOutputStream类
OutputStream
有很多子类,我们从最简单的一个子类开始。
java.io.FileOutputStream
类是文件输出流,用于将数据写出到文件。
输出流的File流(FileOutputStream、FileWriter)一旦创建(new),就会开始写(或者已存在)这个文件,close后就会生成文件。
输入流的File流(FileInputStream、FileReader) 一旦创建(new),如果没有该文件会报错。
构造方法
public FileOutputStream(File file)
:创建文件输出流以写入由指定的 File对象表示的文件。public FileOutputStream(String name)
: 创建文件输出流以指定的名称写入文件。
当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有这个文件,会创建该文件。如果有这个文件,会清空这个文件的数据。
- 构造举例,代码如下:
public class FileOutputStreamConstructor throws IOException {
public static void main(String[] args) {
// 使用File对象创建流对象
File file = new File("a.txt");
FileOutputStream fos1 = new FileOutputStream(file);
// 使用文件名称创建流对象
FileOutputStream fos2 = new FileOutputStream("b.txt");
//前面两个在底层其实是一回事
fos1.write(97);//在文件中写出a
fos1.close();
fos2.close();
}
}
写出字节数据
-
写出字节:
write(int b)
方法,每次可以写出一个字节数据,代码上面这里写了,虽然传int,但会转码小贴士:
- 虽然参数为int类型四个字节,但是只会保留一个字节的信息写出。
- 流操作完毕后,必须释放系统资源,调用close方法,千万记得。
-
写出字节数组:
write(byte[] b)
,每次可以写出数组中的数据,代码使用演示:
public class FOSWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("fos.txt");
//第一种==================================================================
byte[] b = {97,98,99,100,101};
// 写出字节数组数据
//第二种(常用)==================================================================
//byte[] getBytes();返回字符串对应的数组
byte[] b = "abcde".getBytes;
fos.write(b);
// 关闭资源
fos.close();
}
}
- 写出指定长度字节数组:
write(byte[] b, int off, int len)
,每次写出从off索引开始,len个字节,代码使用演示:
public class FOSWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileOutputStream fos = new FileOutputStream("fos.txt");
// 字符串转换为字节数组
byte[] b = "abcde".getBytes();
// 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
fos.write(b,2,2);//文件结果里是cd
// 关闭资源
fos.close();
}
}
换行:fos.write(“\r\n”);
windows:\r\n linux:\n max:\n
数据追加续写
经过以上的演示,每次程序运行,创建输出流对象,都会清空目标文件中的数据。如何保留目标文件中数据,还能继续添加新数据呢?
public FileOutputStream(File file, boolean append)
: 创建文件输出流以写入由指定的 File对象表示的文件。public FileOutputStream(String name, boolean append)
: 创建文件输出流以指定的名称写入文件。
参数中都需要传入一个boolean类型的值,true
表示追加数据续写,false
表示清空原有数据重写。这样创建的输出流对象,就可以指定是否追加续写了。
try,catch,finally要用,原因https://www.bilibili.com/video/BV1gb411F76B?p=284&share_source=copy_web
public class Demo02TryCatchFinally {
public static void main(String[] args) {
//加入finally来实现释放资源
FileOutputStream fos = null;
try {
fos = new FileOutputStream("Javabase\\fos.txt");
// fos = new FileOutputStream("Z:\\Javabase\\fos.txt");
fos.write("hello".getBytes());
}catch (IOException e) {
e.printStackTrace();
} finally {//以防上面过程中错误,没有关闭流
if (fos != null) {//这一行以防输出流发生错误
try {
fos.close();
} catch (IOException e) {//以防close的异常
e.printStackTrace();
}
}
}
}
}
InputStream[字节输入流]
java.io.InputStream
抽象类是表示字节输入流的所有类的超类,可以读取字节信息到内存中。它定义了字节输入流的基本共性功能方法。
public void close()
:关闭此输入流并释放与此流相关联的任何系统资源。public abstract int read()
: 从输入流读取数据的下一个字节,返回这个字节。public int read(byte[] b)
: 从输入流中读取一些字节数,并将它们存储到字节数组 b中 。
小贴士:
close方法,当完成流的操作时,必须调用此方法,释放系统资源。
问题:为什么read()方法读取字节返回的是int而不是byte呢?
答:因为字节输入流可以操作任意类型的文件,比如图片音频等,这些文件底层都是以二进制形式存储的。如果每次读取都返回byte,有可能在读到中间的时候遇到11111111,那么这11111111是byte类型的-1,我们的程序是遇到-1就会停止不读了,后面的数据就读不到了,所以在读取的时候用int类型接收。如果是11111111就会在其前面补上24个0凑足4个字节,那么byte类型的-1就会变成int类型的255了,这样就可以保证整个数据读完,而结束标记的-1就是int类型。
FileInputStream类
java.io.FileInputStream
类是文件输入流,从文件中读取字节。
构造方法
FileInputStream(File file)
: 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。FileInputStream(String name)
: 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。
当你创建一个流对象时,必须传入一个文件路径。该路径下,如果没有该文件,会抛出FileNotFoundException
- 构造举例,代码如下:
public class FileInputStreamConstructor throws IOException{
public static void main(String[] args) {
// 使用File对象创建流对象
File file = new File("a.txt");
FileInputStream fos = new FileInputStream(file);
// 使用文件名称创建流对象
FileInputStream fos = new FileInputStream("b.txt");
}
}
读取字节数据
- 读取字节:
read
方法,每次可以读取一个字节的数据,提升为int类型,读取到文件末尾,返回-1
,代码使用演示:
public class Demo01 {
public static void main(String[] args) throws IOException {
InputStream fis = new FileInputStream("Javabase\\fos.txt");
//如果达到末尾read返回:-1
/*int read = fis.read();
while(read!=-1){
System.out.print((char)read);
read=fis.read();
}*/
//优化上面代码
int read ;
while((read=fis.read())!=-1){
System.out.print((char)read);
}
fis.close();
}
}
- 使用字节数组读取:
read(byte[] b)
,每次读取b的长度个字节到数组中,返回读取到的有效字节个数,读取到末尾时,返回-1
,代码使用演示:
public class Demo02 {
public static void main(String[] args) throws IOException {
InputStream fis = new FileInputStream("Javabase\\fos.txt");//里面是hello换行world
//调用字节输入流对象的读数据方法
//int read (byte[] b):从该输入流读取最多 b.Length个字节的数据到一个字节数组
byte[] bys = new byte[5];
//第一次读取数据
int len = fis.read(bys);
System.out.println(len);
//String (byte[] bytes)把字节数组转换为字符串
System.out.println(new String(bys));
//第二次读取数据
len = fis.read(bys);
System.out.println(len);
System.out.println(new String(bys));
//第三次读取数据
len = fis.read(bys);
System.out.println(len);
System.out.println(new String(bys));
/*
hello\r\n
world
第一次:heLLo
第二次:\r\nwor
第三次:ldwor 第三次因为后三个没有,所以wor是数组里没有变
*/
}
}
数组中,上次读取的数据没有被完全替换,所以要通过len
,获取有效的字节,代码使用演示:
public class FISRead {
public static void main(String[] args) throws IOException{
FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
// 定义变量,作为有效个数
int len;
// 定义字节数组,作为装字节数据的容器
byte[] b = new byte[1024];//建议1024整数倍
// 循环读取
//String(byte[] bytes,int offset,int length)字节数组一部分转换为字符串
while (( len= fis.read(b))!=-1) {
// 每次读取后,把数组的有效字节部分,变成字符串打印
System.out.println(new String(b,0,len));// len 每次读取的有效字节个数
}
// 关闭资源
fis.close();
}
}
复制文本文件(使用字节)
需求:把”E:\IDEA\idea_test\src\fos.txt"复制到模块目录下的“qyp.txt”
思路:
- 根据数据源创建字节输入流对象
- 根据目的地创建字节输出流对象
- 读写数据,复制文本文件(一次读取一个字节,一次写入一个字节)
- 释放资源
public class Copy_Demo {
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream("idea_test\\src\\fos.txt");
FileOutputStream fos=new FileOutputStream("idea_test\\src\\qyp.txt");
int by;
while ((by=fis.read())!=-1){
fos.write(by);
}
fis.close();
fos.close();
}
}
复制图片(使用字节数组)
- 需求:把”E:\qyp.JPG“复制到模块目录下的”mn.jpg“
- 思路:
- 1.根据数据源创建字节输入流
- 2.根据目的地创建字节输出流
- 3.读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组)
- 4.释放资源
public class Copy_Demo {
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream("E:\\qyp.jpg");
FileOutputStream fos=new FileOutputStream("idea_test\\src\\mn.jpg");
//一次读取一个字节数组,一次写入一个字节数组
byte[] bys=new byte[1024];
int len;
while ((len=fis.read(bys))!=-1){
fos.write(bys);
}
fis.close();
fos.close();
}
}
字节缓冲流【Buffered】
-
BufferedOutputStream
:该类实现缓冲输出流。通过设置 这样的输出流,应用程序可以向底层输出流写入字节,而不必为写入的每个字节导致底层系统的调用 -
BufferedInputStream
:创建BufferedInputStream将创建一 个内部缓冲区数组。当从流中读取或跳过字节时,内部缓冲区将根据需要从所包含的输入流中重新填充,一次很多字节
构造方法:
- 字节缓冲输出流:BufferedOutputStream(OutputStream out)
- 字节缓冲输入流:BufferedInputStream(InputStream in)
为什么构造方法需要的是字节流,而不是具体的文件或路径呢?
- 字节缓冲流仅仅提供缓冲区,而真正的读写数据还得依靠基本的字节流对象进行操作
理解:在内存和硬盘之间读写,速度可能差异较大,太占用内存时间(或底层系统的时间),所以引入一个缓冲流,这样数据先读写放入缓冲流中,读写完毕再从缓冲流一次性读写到硬盘或内存。
BufferedOutputStream(OutputStream out):
public class Demo01 {
public static void main(String[] args) throws IOException {
//字节缓冲输出流:BufferedOutputStream(OutputStream out)
// FileOutputStream fos = new FileOutputStream("myByteStreamllbos.txt");
// BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStreamllbos.txt"));
//写数据
bos.write("hello\r\n".getBytes());
bos.write("world\r\n".getBytes());
//释放资源
bos.close();
}
}
BufferedInputStream(InputStream in):
public class Demo02 {
public static void main(String[] args) throws IOException {
//字节缓冲输入流:BufferedInputStream(InputStream in)
BufferedInputStream bis = new BufferedInputStream(new FileInputStream( "myByteStreamllbos.txt"));
/*//一次读取一个字节数据
int by;
while ((by=bis.read())!=-1) {
System.out.print((char)by);
}*/
//一次读取一个字节数组数据
byte[] bys = new byte[1024];
int len;
while ((len=bis.read(bys))!=-1) {
System.out.print(new String(bys,0,len));
}
}
}
字节流复制视频
需求:把”F:\47.avi“复制到模块目录下
思路:
1.根据数据源创建字节输入流
2.根据目的地创建字节输出流
3.读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组
4.释放资源
四种实现方式复制视频,并记录每种方式复制视频的时间
- 1.基本字节流一次读写一个字节 共耗时:9319毫秒
- 2.基本字节流一次读取一个字节数组 共耗时:69毫秒
- 3.字节缓冲流一次读取一个字节 共耗时:127毫秒
- 4.字节缓冲流一次读取一个字节数组 共耗时:8毫秒` ***最快
public class Demo03CopyAvi {
public static void main(String[] args) throws IOException {
long startTime = System.currentTimeMillis();
// method1();//共耗时:9319毫秒
// method2();//共耗时:69毫秒
// method3();//共耗时:127毫秒
method4();//共耗时:8毫秒
long stopTime = System.currentTimeMillis();
System.out.println("共耗时:" + (stopTime - startTime) + "毫秒");
}
public static void method1() throws IOException {
FileInputStream fis = new FileInputStream("F:\\47.mp4");
FileOutputStream fos = new FileOutputStream("G:\\47.mp4");
int by;
while ((by = fis.read()) != -1) {
fos.write(by);
}
fos.close();
fis.close();
}
public static void method2() throws IOException {
FileInputStream fis = new FileInputStream("F:\\47.mp4");
FileOutputStream fos = new FileOutputStream("G:\\47.mp4");
byte[] by = new byte[1024];
int len;
while ((len = fis.read(by)) != -1) {
fos.write(by, 0, len);
}
fos.close();
fis.close();
}
public static void method3() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("F:\\47.mp4"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("G:\\47.mp4"));
int by;
while ((by = bis.read()) != -1) {
bos.write(by);
}
bos.close();
bis.close();
}
public static void method4() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("F:\\47.mp4"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("G:\\47.mp4"));
byte[] bys = new byte[1024];
int len;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
二、字符流
当使用字节流读取文本文件时,可能会有一个小问题。就是遇到中文字符时,可能不会显示完整的字符,那是因为一个中文字符可能占用多个字节存储。所以Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文件。
一个汉字存储
-
GBK编码:占用两个字节 中国——>[-42,-48,-71,-6]
-
UTF-8编码:占用3个字节 中国——>[-28,-72,-83,-27,-101,-67]
可以发现汉字在存储的时候,第一个字符都是负数
由于字节流操作中文不是特别的方便,所以Java就提供字符流
字符流=字节流+编码表
用字节流复制文本文件时,文本文件也会有中文,但是没有问题,原因是最终底层操作会自动进行字节拼接成
中文,如何识别是中文的呢?
- 汉字在存储的时候,无论选择哪种编码存储,第一个字节都是负数
编码表
基础知识:
- 计算机中储存的信息都是用二进制数表示的; 我们在屏幕上看到的英文、汉字等字符是二进制数转换之后
的结果 - 按照某种规则,将字符存储到计算机中,称为编码。反之,将存储在计算机中的二进制数按照某种规则解析显示出来,称为解码。
- 这里强调一下:按照A编码存储,必须按照A编码解析,这样才能显示正确的文本符号。否则就会导致乱码
- 字符编码:就是一套自然语言的字符与二进制数之间的对应规则(A,65)
ASCII字符集:
-
ASCII(American Standard Code for Information Interchange,美国信息交换标准代码):是基于拉丁
字母的一套电脑编码系统,用于显示现代英语,主要包括控制字符(回车键、退格、换行键等)和可显示字
符(英文大小写字符、阿拉伯数字和西文符号) -
基本的ASCII字符集,使用7位表示一个字符,共128字符。ASCII的扩展字符集使用8位表示一个字符,共
256字符,方便支持欧洲常用字符。是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图
形符号、数字等。
GBXXX字符集:
GB2312
:简体中文码表。一个小于127的字符的意义与原来相同,但两个大于127的字符连在一起时,
就表示一个汉字,这样大约可以组合了包含7000多个简体汉字,此外数学符号、罗马希腊的字母、日文
的假名等都编进去了,连在ASCII里本来就有的数字、标点、字母都统统重新编了两个字节长的编码,这
就是常说的"全角"字符,而原来在127号以下的那些就叫"半角"字符了- GBK:最常用的中文码表。是在GB2312标准基础上的扩展规范,使用了双字节编码方案,共收录了
21003个汉字,完全兼容GB2312标准,同时支持繁体汉字以及日韩汉字等 GB18030
:最新的中文码表。收录汉字70244个,采用多字节编码,每个字可以由1个、2个或4个字节组
成。支持中国国内少数民族的文字,同时支持繁体汉字以及日韩汉字等
Unicode字符集:
-
为表达任意语言的任意字符而设计,是业界的一种标准,也称为统一码、标准万国码。它最多使用4个字
节的数字来表达每个字母、符号,或者文字。有三种编码方案,UTF-8、UTF-16和UTF32。最为常用的
UTF-8编码 -
UTF-8编码:可以用来表示Unicode标准中任意字符,它是电子邮件、网页及其他存储或传送文字的应用
中,优先采用的编码。互联网工程工作小组(IETF)要求所有互联网协议都必须支持UTF-8编码。它使用
一至四个字节为每个字符编码编码规则:
128个US-ASCII字符,只需一个字节编码
拉丁文等字符,需要二个字节编码
大部分常用字(含中文),使用三个字节编码
其他极少使用的Unicode辅助字符,使用四字节编码
注:采用何种规则编码,就要采用对应规则解码,否则就会出现乱码
解码编码
编码:
-
byte[ ] getBytes()
:使用平台的默认字符集将该 String编码为一系列字节,将结果存储到新的字节数组中 -
byte[] getBytes(String charsetName)
:使用指定的字符集将该 String编码为一系列字节,将结果存储到新的字节数组中
解码:
String(byte[] bytes)
:通过使用平台的默认字符集解码指定的字节数组来构造新的 StringString(byte[] bytes, String charsetName)
:通过指定的字符集解码指定的字节数组来构造新的 String
字符流抽象基类:
- Reader:字符输入流的抽象类; 常用实现类:InputStreamReader(可指定字符集)/FileReader(默认字符集)
- Writer:字符输出流的抽象类; 常用实现类:OutputStreamWriter(可指定字符集)/FileWriter(默认字符集)
字符输入流【Reader】
java.io.Reader
抽象类是表示用于读取字符流的所有类的超类,可以读取字符信息到内存中。它定义了字符输入流的基本共性功能方法。
public void close()
:关闭此流并释放与此流相关联的任何系统资源。public int read()
: 从输入流读取一个字符。public int read(char[] cbuf)
: 从输入流中读取一些字符,并将它们存储到字符数组 cbuf中 。
FileReader类
java.io.FileReader
类是读取字符文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。
小贴士:
字符编码:字节与字符的对应规则。Windows系统的中文编码默认是GBK编码表。
idea中UTF-8
字节缓冲区:一个字节数组,用来临时存储字节数据。
构造方法
FileReader(File file)
: 创建一个新的 FileReader ,给定要读取的File对象。FileReader(String fileName)
: 创建一个新的 FileReader ,给定要读取的文件的名称。
当你创建一个流对象时,必须传入一个文件路径。类似于FileInputStream 。
- 构造举例,代码如下:
public class FileReaderConstructor throws IOException{
public static void main(String[] args) {
// 使用File对象创建流对象
File file = new File("a.txt");
FileReader fr = new FileReader(file);
// 使用文件名称创建流对象
FileReader fr = new FileReader("b.txt");
}
}
12345678910
读取字符数据
- 读取字符:
read
方法,每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回-1
,循环读取,代码使用演示:
public class FRRead {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileReader fr = new FileReader("read.txt");
// 定义变量,保存数据
int b ;
// 循环读取
while ((b = fr.read())!=-1) {
System.out.println((char)b);
}
// 关闭资源
fr.close();
}
}
输出结果:
黑
马
程
序
员
1234567891011121314151617181920
小贴士:虽然读取了一个字符,但是会自动提升为int类型。
- 使用字符数组读取:
read(char[] cbuf)
,每次读取b的长度个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回-1
,代码使用演示:
public class FRRead {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileReader fr = new FileReader("read.txt");
// 定义变量,保存有效字符个数
int len ;
// 定义字符数组,作为装字符数据的容器
char[] cbuf = new char[2];
// 循环读取
while ((len = fr.read(cbuf))!=-1) {
System.out.println(new String(cbuf));
}
// 关闭资源
fr.close();
}
}
输出结果:
黑马
程序
员序
1234567891011121314151617181920
获取有效的字符改进,代码使用演示:
public class FISRead {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileReader fr = new FileReader("read.txt");
// 定义变量,保存有效字符个数
int len ;
// 定义字符数组,作为装字符数据的容器
char[] cbuf = new char[2];
// 循环读取
while ((len = fr.read(cbuf))!=-1) {
System.out.println(new String(cbuf,0,len));
}
// 关闭资源
fr.close();
}
}
输出结果:
黑马
程序
员
123456789101112131415161718192021
字符输出流【Writer】
2022.3.7看bloghttps://blog.csdn.net/qq_35122713/article/details/88793019
博客说Writer其实也有一个缓冲流,在写文件时,在flush()或close()之前是不会写进去的,而是放进缓冲区里
java.io.Writer
抽象类是表示用于写出字符流的所有类的超类,将指定的字符信息写出到目的地。它定义了字节输出流的基本共性功能方法。
void write(int c)
写入单个字符。void write(char[] cbuf)
写入字符数组。abstract void write(char[] cbuf, int off, int len)
写入字符数组的某一部分,off数组的开始索引,len写的字符个数。void write(String str)
写入字符串。void write(String str, int off, int len)
写入字符串的某一部分,off字符串的开始索引,len写的字符个数。void flush()
刷新该流的缓冲。void close()
关闭此流,但要先刷新它。
FileWriter类
java.io.FileWriter
类是写出字符到文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。
构造方法
FileWriter(File file)
: 创建一个新的 FileWriter,给定要读取的File对象。FileWriter(String fileName)
: 创建一个新的 FileWriter,给定要读取的文件的名称。
当你创建一个流对象时,必须传入一个文件路径,类似于FileOutputStream。
- 构造举例,代码如下:
public class FileWriterConstructor {
public static void main(String[] args) throws IOException {
// 使用File对象创建流对象
File file = new File("a.txt");
FileWriter fw = new FileWriter(file);
// 使用文件名称创建流对象
FileWriter fw = new FileWriter("b.txt");
}
}
12345678910
基本写出数据
写出字符:write(int b)
方法,每次可以写出一个字符数据,代码使用演示:
public class FWWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileWriter fw = new FileWriter("fw.txt");
// 写出数据
fw.write(97); // 写出第1个字符
fw.write('b'); // 写出第2个字符
fw.write('C'); // 写出第3个字符
fw.write(30000); // 写出第4个字符,中文编码表中30000对应一个汉字。
/*
【注意】关闭资源时,与FileOutputStream不同。
如果不关闭,数据只是保存到缓冲区,并未保存到文件。
*/
// fw.close();
}
}
输出结果:
abC田
12345678910111213141516171819
小贴士:
- 虽然参数为int类型四个字节,但是只会保留一个字符的信息写出。
- 未调用close方法,数据只是保存到了缓冲区,并未写出到文件中。
关闭和刷新
因为内置缓冲区的原因,如果不关闭输出流,无法写出字符到文件中。但是关闭的流对象,是无法继续写出数据的。如果我们既想写出数据,又想继续使用流,就需要flush
方法了。
flush
:刷新缓冲区,流对象可以继续使用。close
:先刷新缓冲区,然后通知系统释放资源。流对象不可以再被使用了。
个人理解:可能只要有缓冲区,都需要有flush来刷新缓冲区(PrintWriter不清楚,它可能有缓冲区,但是默认不用flush,可能是封装了flush方法)
代码使用演示:
public class FWWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileWriter fw = new FileWriter("fw.txt");
// 写出数据,通过flush
fw.write('刷'); // 写出第1个字符
fw.flush();
fw.write('新'); // 继续写出第2个字符,写出成功
fw.flush();
// 写出数据,通过close
fw.write('关'); // 写出第1个字符
fw.close();
fw.write('闭'); // 继续写出第2个字符,【报错】java.io.IOException: Stream closed
fw.close();
}
}
1234567891011121314151617
小贴士:即便是flush方法写出了数据,操作的最后还是要调用close方法,释放系统资源。
写出其他数据
- 写出字符数组 :
write(char[] cbuf)
和write(char[] cbuf, int off, int len)
,每次可以写出字符数组中的数据,用法类似FileOutputStream,代码使用演示:
public class FWWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileWriter fw = new FileWriter("fw.txt");
// 字符串转换为字节数组
char[] chars = "黑马程序员".toCharArray();
// 写出字符数组
fw.write(chars); // 黑马程序员
// 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
fw.write(b,2,2); // 程序
// 关闭资源
fos.close();
}
}
1234567891011121314151617
- 写出字符串:
write(String str)
和write(String str, int off, int len)
,每次可以写出字符串中的数据,更为方便,代码使用演示:
public class FWWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileWriter fw = new FileWriter("fw.txt");
// 字符串
String msg = "黑马程序员";
// 写出字符数组
fw.write(msg); //黑马程序员
// 写出从索引2开始,2个字节。索引2是'程',两个字节,也就是'程序'。
fw.write(msg,2,2); // 程序
// 关闭资源
fos.close();
}
}
1234567891011121314151617
- 续写和换行:操作类似于FileOutputStream。
public class FWWrite {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象,可以续写数据
FileWriter fw = new FileWriter("fw.txt",true);
// 写出字符串
fw.write("黑马");
// 写出换行
fw.write("\r\n");
// 写出字符串
fw.write("程序员");
// 关闭资源
fw.close();
}
}
输出结果:
黑马
程序员
1234567891011121314151617
小贴士:字符流,只能操作文本文件,不能操作图片,视频等非文本文件。
当我们单纯读或者写文本文件时 使用字符流 其他情况使用字节流
字符缓冲流【Buffered】
字符缓冲流:
-
BufferedWriter
:将文本写入字符输出流,缓冲字符,以提供单个字符,数组和字符串的高效写入,可
以指定缓冲区大小,或者可以接受默认大小。默认值足够大,可用于大多数用途 -
BufferedReader
:从字符输入流读取文本,缓冲字符,以提供字符,数组和行的高效读取,可以指定
缓冲区大小,或者可以使用默认大小。默认值足够大,可用于大多数用途
构造方法:
-
BufferedWriter(Writer out)
-
BufferedReader(Reader in)
特有方法
字符缓冲流的基本方法与普通字符流调用方式一致,不再阐述,我们来看它们具备的特有方法。
- BufferedReader:
public String readLine()
: 读一行文字。 - BufferedWriter:
public void newLine()
: 写一行行分隔符,由系统属性定义符号。
读:readLine
方法演示,代码如下:
public class BufferedReaderDemo {
public static void main(String[] args) throws IOException {
// 创建流对象
BufferedReader br = new BufferedReader(new FileReader("in.txt"));
// 定义字符串,保存读取的一行文字
String line = null;
// 循环读取,读取到最后返回null
while ((line = br.readLine())!=null) {
System.out.print(line);
System.out.println("------");
}
// 释放资源
br.close();
}
}
写:newLine
方法演示,代码如下:
public class BufferedWriterDemo throws IOException {
public static void main(String[] args) throws IOException {
// 创建流对象
BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
// 写出数据
bw.write("黑马");
// 写出换行
bw.newLine();
bw.write("程序");
bw.newLine();
bw.write("员");
bw.newLine();
// 释放资源
bw.close();
}
}
输出效果:
黑马
程序
员
字符转换流
这里说的转换应该是编码的转换吧
编码引出的问题
在IDEA中,使用FileReader
读取项目中的文本文件。由于IDEA的设置,都是默认的UTF-8
编码,所以没有任何问题。但是,当读取Windows系统中创建的文本文件时,由于Windows系统的默认是GBK编码,就会出现乱码。
public class ReaderDemo {
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("E:\\File_GBK.txt");
int read;
while ((read = fileReader.read()) != -1) {
System.out.print((char)read);
}
fileReader.close();
}
}
输出结果:
���
那么如何读取GBK编码的文件呢?
InputStreamReader类
转换流java.io.InputStreamReader
,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定的字符集将其解码为字符。它的字符集可以由名称指定,也可以接受平台的默认字符集。
构造方法
InputStreamReader(InputStream in)
: 创建一个使用默认字符集的字符流。InputStreamReader(InputStream in, String charsetName)
: 创建一个指定字符集的字符流。
构造举例,代码如下:
InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));
InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");
指定编码读取
public class ReaderDemo2 {
public static void main(String[] args) throws IOException {
// 定义文件路径,文件为gbk编码
String FileName = "E:\\file_gbk.txt";
// 创建流对象,默认UTF8编码
InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName));
// 创建流对象,指定GBK编码
InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName) , "GBK");
// 定义变量,保存字符
int read;
// 使用默认编码字符流读取,乱码
while ((read = isr.read()) != -1) {
System.out.print((char)read); // ��Һ�
}
isr.close();
// 使用指定编码字符流读取,正常解析
while ((read = isr2.read()) != -1) {
System.out.print((char)read);// 大家好
}
isr2.close();
}
}
OutputStreamWriter类
转换流java.io.OutputStreamWriter
,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。
构造方法
OutputStreamWriter(OutputStream in)
: 创建一个使用默认字符集的字符流。OutputStreamWriter(OutputStream in, String charsetName)
: 创建一个指定字符集的字符流。
构造举例,代码如下:
OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("out.txt"));
OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("out.txt") , "GBK");
12
指定编码写出
public class OutputDemo {
public static void main(String[] args) throws IOException {
// 定义文件路径
String FileName = "E:\\out.txt";
// 创建流对象,默认UTF8编码
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName));
// 写出数据
osw.write("你好"); // 保存为6个字节
osw.close();
// 定义文件路径
String FileName2 = "E:\\out2.txt";
// 创建流对象,指定GBK编码
OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK");
// 写出数据
osw2.write("你好");// 保存为4个字节
osw2.close();
}
}
转换流理解图解
转换流是字节与字符间的桥梁!
练习:转换文件编码
将GBK编码的文本文件,转换为UTF-8编码的文本文件。
案例分析
- 指定GBK编码的转换流,读取文本文件。
- 使用UTF-8编码的转换流,写出文本文件。
案例实现
public class TransDemo {
public static void main(String[] args) {
// 1.定义文件路径
String srcFile = "file_gbk.txt";
String destFile = "file_utf8.txt";
// 2.创建流对象
// 2.1 转换输入流,指定GBK编码
InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile) , "GBK");
// 2.2 转换输出流,默认utf8编码
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destFile));
// 3.读写数据
// 3.1 定义数组
char[] cbuf = new char[1024];
// 3.2 定义长度
int len;
// 3.3 循环读取
while ((len = isr.read(cbuf))!=-1) {
// 循环写出
osw.write(cbuf,0,len);
}
// 4.释放资源
osw.close();
isr.close();
}
}
标准输入输出流
System类中有两个静态的成员变量:
public static final InputStream in
:标准输入流。通常该流对应于键盘输入或由主机环境或用户指定的另一个输入源public static final PrintStream out
:标准输出流。通常该流对应于显示输出或由主机环境或用户指定的另一个输出目标
输入流
自己实现键盘录入数据:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
写起来太麻烦,Java就提供了一个类实现键盘录入
Scanner sc = new Scanner(System.in);
输出流
输出语句的本质:是一个标准的输出流
PrintStream ps = System.out;
PrintStream类有的方法, System.out都可以使用
打印流
概述
平时我们在控制台打印输出,是调用print
方法和println
方法完成的,这两个方法都来自于java.io.PrintStream
类,该类能够方便地打印各种数据类型的值,是一种便捷的输出方式。
- PrintStream
- PrintWriter
PrintStream类
- java.lang.Object
-
- java.io.OutputStream
-
- java.io.FilterOutputStream
-
- java.io.PrintStream
构造方法
public PrintStream(String fileName)
: 使用指定的文件名创建一个新的打印流。字节打印流public Printstream(Outputstream os)
: 打印流直接通向字节输出流管道public PrintStream(File f)
: 打印流直接通向文件对象
构造举例,代码如下:
PrintStream ps = new PrintStream("ps.txt");
案例:
try(
PrintStream printStream = new PrintStream(new FileOutputStream("hello-app/src/data.txt", true));
){
printStream.println("====================================");
} catch(Exception e) {
e.printStackTrace();
}
好像把资源放到小括号里会自动释放资源
常用方法
public void print(Object obj)
: 打印一个对象。也可以是基本类型或其数组boolean/char/char[]/double/flout/int。。。public void println(Object obj)
: 打印一个对象并换行。也可以是基本类型或其数组boolean/char/char[]/double/flout/int。。。public void write(byte[] buf, int off, int len)
: 从指定的字节数组写入len
个字节,从偏移off
开始到此流。public void write(int b)
: 将指定的字节写入此流。
注意:print()和println()都是将其中参数转换成字符串之后,再写入到输入流。
例如,print(0x61);
等价于
write(String.valueOf(0x61));
上面语句是将字符串"97"写入到输出流。0x61对应十进制数是97。
write(0x61)
个人浅浅的理解:
print(x)会调用String.valueOf(x),write(int x)会直接把x以字节的形式写入
改变打印流向
System.out
就是PrintStream
类型的(print/println),只不过它的流向是系统规定的,打印在控制台上。不过,既然是流对象,我们就可以玩一个"小把戏",改变它的流向。
public class PrintDemo {
public static void main(String[] args) throws IOException {
// 调用系统的打印流,控制台直接输出97
System.out.println(97);
// 创建打印流,指定文件的名称
PrintStream ps = new PrintStream("ps.txt");
// 设置系统的打印流流向,输出到ps.txt
System.setOut(ps);
// 调用系统的打印流,ps.txt中输出97
System.out.println(97);
}
}
字符打印流:PrintWriter
-
- java.io.Writer
-
- java.io.PrintWriter
-
PrintWriter(String fileName) 使用指定文件名创建新的打印流,而不需要自动执行刷新
PrintWriter和PrintStream虽然父系不一样,但常用方法基本类似,用法也几乎一样
PrintWriter和PrintStream区别呢?
答:我目前只知道PrintStream主要操作byte流,而PrintWriter用来操作[字符流](无法处理字节流)。读取文本文件时一般用后者。
打印流特点:
- 只负责输出数据,不负责读取数据
- 有自己的特有方法
序列化
Java 提供了一种对象序列化的机制。用一个字节序列可以表示一个对象,该字节序列包含该对象的数据
、对象的类型
和对象中存储的属性
等信息。字节序列写出到文件之后,相当于文件中持久保存了一个对象的信息。
反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化。对象的数据
、对象的类型
和对象中存储的数据
信息,都可以用来在内存中创建对象。看图理解序列化:
要实现序列化和反序列化就要使用对象序列化流和对象反序列化流:
- 对象序列化流:
ObjectOutputStream
- 对象反序列化流:
ObjectInputStream
ObjectOutputStream类
java.io.ObjectOutputStream
类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。
构造方法
public ObjectOutputStream(OutputStream out)
: 创建一个指定OutputStream的ObjectOutputStream。
构造举例,代码如下:
FileOutputStream fileOut = new FileOutputStream("employee.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
序列化操作
- 一个对象要想序列化,必须满足两个条件:
- 该类必须实现
java.io.Serializable
接口,Serializable
是一个标记接口,不实现此接口的类将不会使任何状态序列化或反序列化,会抛出NotSerializableException
。 - 该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态的,使用
transient
关键字修饰。
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int age; // transient瞬态修饰成员,不会被序列化
public void addressCheck() {
System.out.println("Address check : " + name + " -- " + address);
}
}
2.写出对象方法
public final void writeObject (Object obj)
: 将指定的对象写出。
public class SerializeDemo{
public static void main(String [] args) {
Employee e = new Employee();
e.name = "zhangsan";
e.address = "beiqinglu";
e.age = 20;
try {
// 创建序列化流对象
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt"));
// 写出对象
out.writeObject(e);
// 释放资源
out.close();
fileOut.close();
System.out.println("Serialized data is saved"); // 姓名,地址被序列化,年龄没有被序列化。
} catch(IOException i) {
i.printStackTrace();
}
}
}
输出结果:
Serialized data is saved
ObjectInputStream类
ObjectInputStream反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象。
构造方法
public ObjectInputStream(InputStream in)
: 创建一个指定InputStream的ObjectInputStream。
反序列化操作1
如果能找到一个对象的class文件,我们可以进行反序列化操作,调用ObjectInputStream
读取对象的方法:
public final Object readObject ()
: 读取一个对象。
public class DeserializeDemo {
public static void main(String [] args) {
Employee e = null;
try {
// 创建反序列化流
FileInputStream fileIn = new FileInputStream("employee.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
// 读取一个对象
e = (Employee) in.readObject();
// 释放资源
in.close();
fileIn.close();
}catch(IOException i) {
// 捕获其他异常
i.printStackTrace();
return;
}catch(ClassNotFoundException c) {
// 捕获类找不到异常
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
// 无异常,直接打印输出
System.out.println("Name: " + e.name); // zhangsan
System.out.println("Address: " + e.address); // beiqinglu
System.out.println("age: " + e.age); // 0
}
}
对于JVM可以反序列化对象,它必须是能够找到class文件的类。如果找不到该类的class文件,则抛出一个 ClassNotFoundException
异常。
反序列化操作2
另外,当JVM反序列化对象时,能找到class文件,但是class文件在序列化对象之后发生了修改,那么反序列化操作也会失败,抛出一个InvalidClassException
异常。**发生这个异常的原因如下:
- 该类的序列版本号与从流中读取的类描述符的版本号不匹配
- 该类包含未知数据类型
- 该类没有可访问的无参数构造方法
Serializable
接口给需要序列化的类,提供了一个序列版本号。serialVersionUID
该版本号的目的在于验证序列化的对象和对应类是否版本匹配。
public class Employee implements java.io.Serializable {
// 加入序列版本号
private static final long serialVersionUID = 1L;
public String name;
public String address;
// 添加新的属性 ,重新编译, 可以反序列化,该属性赋为默认值.
public int eid;
public void addressCheck() {
System.out.println("Address check : " + name + " -- " + address);
}
}
序列化集合
- 将存有多个自定义对象的集合序列化操作,保存到
list.txt
文件中。 - 反序列化
list.txt
,并遍历集合,打印对象信息。
案例分析
- 把若干学生对象 ,保存到集合中。
- 把集合序列化。
- 反序列化读取时,只需要读取一次,转换为集合类型。
- 遍历集合,可以打印所有的学生信息
案例实现
public class SerTest {
public static void main(String[] args) throws Exception {
// 创建 学生对象
Student student = new Student("老王", "laow");
Student student2 = new Student("老张", "laoz");
Student student3 = new Student("老李", "laol");
ArrayList<Student> arrayList = new ArrayList<>();
arrayList.add(student);
arrayList.add(student2);
arrayList.add(student3);
// 序列化操作
// serializ(arrayList);
// 反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("list.txt"));
// 读取对象,强转为ArrayList类型
ArrayList<Student> list = (ArrayList<Student>)ois.readObject();
for (int i = 0; i < list.size(); i++ ){
Student s = list.get(i);
System.out.println(s.getName()+"--"+ s.getPwd());
}
}
private static void serializ(ArrayList<Student> arrayList) throws Exception {
// 创建 序列化流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt"));
// 写出对象
oos.writeObject(arrayList);
// 释放资源
oos.close();
}
}
Properties类
Properties
类表示一组持久的属性。Properties
可以保存到流中或从流中加载。属性列表中的每个键及其对应的值都是一个字符串。
构造方法
public Properties()
:创建一个空的属性列表。
基本的存储方法
public Object setProperty(String key, String value)
: 保存一对属性。public String getProperty(String key)
:使用此属性列表中指定的键搜索属性值。public Set<String> stringPropertyNames()
:所有键的名称的集合。
public class ProDemo {
public static void main(String[] args) throws FileNotFoundException {
// 创建属性集对象
Properties properties = new Properties();
// 添加键值对元素
properties.setProperty("filename", "a.txt");
properties.setProperty("length", "209385038");
properties.setProperty("location", "D:\\a.txt");
// 打印属性集对象
System.out.println(properties);
// 通过键,获取属性值
System.out.println(properties.getProperty("filename"));
System.out.println(properties.getProperty("length"));
System.out.println(properties.getProperty("location"));
// 遍历属性集,获取所有键的集合
Set<String> strings = properties.stringPropertyNames();
// 打印键值对
for (String key : strings ) {
System.out.println(key+" -- "+properties.getProperty(key));
}
}
}
输出结果:
{filename=a.txt, length=209385038, location=D:\a.txt}
a.txt
209385038
D:\a.txt
filename -- a.txt
length -- 209385038
location -- D:\a.txt
与流相关的方法
public void load(InputStream inStream)
: 从字节输入流中读取键值对。
参数中使用了字节输入流,通过流对象,可以关联到某文件上,这样就能够加载文本中的数据了。文本数据格式:
filename=a.txt
length=209385038
location=D:\a.txt
加载代码演示:
public class ProDemo2 {
public static void main(String[] args) throws FileNotFoundException {
// 创建属性集对象
Properties pro = new Properties();
// 加载文本中信息到属性集
pro.load(new FileInputStream("read.txt"));
// 遍历集合并打印
Set<String> strings = pro.stringPropertyNames();
for (String key : strings ) {
System.out.println(key+" -- "+pro.getProperty(key));
}
}
}
输出结果:
filename -- a.txt
length -- 209385038
location -- D:\a.txt
小贴士:文本中的数据,必须是键值对形式,可以使用空格、等号、冒号等符号分隔。