IO流
1. IO流原理及流的分类
Java IO原理
- IO是Input/Outout的缩写,I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等
- Java程序中,对于数据的输入/输出操作以"流(Stream)"的方式进行
- java.io包下提供了各种"流"类和接口,用以获取不同种类的数据,并通过标准的方法输入和输出数据
- 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中
- 输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中
-
按操作数据单位不同分为:字节流(以byte为基本单位 8bit),字符流(以char为基本单位 16bit)
-
按数据流的流向不同分为:输入流,输出流
-
按流的角色的不同分为:节点流,处理流
(抽象基类) 字节流 字符流 输入流 InputStream Reader 输出流 OutputStream Writer
- Java的IO流共涉及40多个类,实际上非常规则,都是从如4个抽象基类派生的
- 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀
IO流体系
2. 字符流 FileReader和FileWriter
2.1 FileReader读入数据的操作
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderWriterTest {
@Test
/*
* 将Demo1下的hello.txt的文件内容读入程序中,并输出到控制台
为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally处理
* */
public void testFileReader() {
// 实例化File类的对象,指明要操作的文件
FileReader fr = null;
try {
File file = new File("hello.txt");//相较与当前Module,相对路径
// 提供具体的流
fr = new FileReader(file);
// 数据的读入
// 返回读入的一个字符,如果达到文件末尾,返回-1
int data;
while ((data = fr.read()) != -1) { //未到达文件末尾,继续向下读入数据
System.out.print((char) data);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//流的关闭操作
try {
if (fr != null)
fr.close();//手动的关闭资源
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
FileReader中使用read(char[] cbuf)读入数据,提高读入数据的效率
通过创建一指定长度的char型数组作为参数,表示每次读入指定长度的数据
创建hello.txt文件输入数据
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf)) != -1) {
/*
方式一
for (int i = 0; i < len; i++) {//每次读入len个数据,就输出len个数据
System.out.print(cbuf[i]);
}*/
/*
方式二
String str=new String(cbuf,0,len);*/
// 方式三
String str=new String(cbuf);
String substring=str.substring(0,len);
System.out.print(substring);
}
2.2 FileReader写出数据的操作
-
从内存中写出数据到磁盘里
输出操作,对应的File可以不存在,如果不存在,在输出的过程中,会自动创建
如果流使用的构造器 FileWriter(file,false)/FileWriter(file):对原有文件覆盖
File file = new File("hello1.txt");//指定事先未创建的文件路径
FileWriter fw = new FileWriter(file);
fw.write("Failure is the mother of success\n");
fw.write("I have a dream");
fw.flush();//如果写出的文件内容空白,调用此方法刷新缓存
程序运行后创建hello1.txt文件并将字符串内容写出到该文件中
如果流使用的构造器FileWriter(file,true):不会对原有文件覆盖,在原有文件后追加内容
FileWriter fw = new FileWriter(file,true);
fw.write("Failure is the mother of success\n");
fw.write("I have a dream");
fw.flush();
2.3 使用FileReader和FileWriter实现文本文件的复制
将一个文件中的内容读入后写出到另一个文件中,实现文本文件内容的复制,步骤与前面读写数据的操作是一致的
FileReader fr = null;
FileWriter fw = null;
try {
// 1.创建File类的对象,指明读入和写出的文件
File srcFile = new File("hello.txt");
File desFile = new File("hello1.txt");
// 2.创建输入流和输出流的对象
fr = new FileReader(srcFile);
fw = new FileWriter(desFile);
// 3.数据的读入和写出操作
char[] cbuf = new char[5];
int len;//每次读入len个字符
while ((len = fr.read(cbuf)) != -1) {
fw.write(cbuf, 0, len);//每次写出len个字符
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
// 4.流的关闭
try {
if (fr != null)
fr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
if (fw != null)
fw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
hello.txt文件中的内容复制到了hello1.txt文件中
2.4 字符流不能实现非文本文件的读写操作
创建非文本文件路径下的对象
File srcFile = new File("繁花似锦.jpg");
File desFile = new File("繁花似锦1.jpg");
FileReader fr = new FileReader(srcFile);
FileWriter fw = new FileWriter(desFile);
文件复复制后发生错误,查看复制后的文件属性
由以上两张图片对比可以看出,复制后的文件大小也发生了变化,印证了使用字符流的方式是无法对非文本文件进行复制的
思考:为什么字符流无法对非文本文件进行赋值?
参考资料发现,文件复制的过程是:
字符流:二进制数据----解码—>字符编码表----编码----二进制数据
字节流:二进制数据-----二进制数据
字符流按字符读数据:
当前编译器使用的是UTF-8字符编码,属于Unicode字符集的一种,在Unicode字符集下,一次读两个字节,返回了这两个字节所对应的字符的int型数值(编码)。写入文件时把这两个字节的内容解码成这个字符在Unicode码下对应的二进制数据写入。
即把原始文件中的二进制数据以字符形式读入,再将字符以二进制形式写出,所以得到的文件以字符方式存储。而图片的数据是按字节存储的,所以打开图片时解码出错了
字节流按字节读数据:而字节不需要编码、解码,只有字节与字符之间转换时才需要编码、解码,所以可以正常读取图片数据。
3. 字节流(文件流) FileInputStream和FileOutputStream
3.1 使用FileInputStream进行读取文本文件测试
FileInputStream fis = null;
try {
File file = new File("hello.txt");
fis = new FileInputStream(file);
byte[] buffer = new byte[5];
int len;
while ((len=fis.read(buffer))!=-1){
String str = new String(buffer, 0, len);
System.out.print(str);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if(fis!=null)
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
在这里可以看到hello.txt文件中的内容能够被读入并正常输出,这是因为一个英文字符占一个字节,按照字节流读入时一个字节就是一个字符,所以可以正常读入。
- 在UTF-8编码中,一个英文字符等于一个字节,一个中文(含繁体)等于三个字节。中文标点占三个字节,英文标点占一个字节
如果文件中含有中文字符,在读入输出时会出现乱码
如果读入的数据长度剩余的字节空间小于一个汉字所占用的字节空间,那个汉字的字节会被分成两半,出现乱码
结论:
- 对于文本文件(.txt,.java,.c,.cpp),使用字符流进行处理
- 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理
3.2 使用FileInputStream和FileOutputStream读写非文本文件
在当前模块下导入图片文件
这里进行图片文件的读取和复制与字符流方式的实现是完全一致的
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcFile = new File("繁花似锦.jpg");
File desFile = new File("繁花似锦1.jpg");
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(desFile);
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer,0,len);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
创建新的jpg文件,将原文件图片复制到了新的文件中
3.3 实现指定路径下文件的复制
将上述文件复制的操作可写成一个通用的方法,
定义一个带有两个参数的方法,传入要复制的源文件和目标文件
public void copyFile(String srcpath,String destPath)
将参数传入File类创建的路径对象中,
File srcFile = new File(srcpath);
File desFile = new File(destPath);
通过对视频文件的复制操作来体现该方法,
public void testCopyFile(){
long start=System.currentTimeMillis();
String srcPath = new String("C:\\Users\\Administrator\\Pictures\\Saved Pictures\\video2.mp4");
String destPath = new String("C:\\Users\\Administrator\\Pictures\\Saved Pictures\\video3.mp4");
copyFile(srcPath,destPath) ;
long end=System.currentTimeMillis();
System.out.println("复制操作花费的时间为"+(end-start));
}
调用已经定义好的copyFile方法,实现了对视频文件的复制,点击查看视频文件的属性
文件复制后的大小是一致的,表示该文件完整的复制到其指定路径中
将非文本文件的读写操作用到文本文件中,也是可以的
public void testCopyFile1(){
String srcPath = new String("hello.txt");
String destPath = new String("hello1.txt");
copyFile(srcPath,destPath) ;
}
复制之后并没有出现乱码,这是因为在复制过程中没有出现字节与字符之间的转换,以字节的方式读入,立刻又以字节的方式写出到hello1.txt文件中
4. 缓冲流
4.1 缓冲流(字节型)实现非文本文件的复制
缓冲流属于处理流的一种,缓冲流的作用是为了提高文件的读写效率。在开发当中,不会使用以上的四个节点流,因为在效率上是差一些的
缓冲流是包在当前节点流外层的,在原代码上添加缓冲流
字节型中缓冲流中用到的是 BufferedInputStream 和 BufferedOutputStream
File srcFile = new File("繁花似锦.jpg");
File destFile = new File("繁花似锦2.jpg");
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos=new FileOutputStream(destFile);
//在当前节点流外层包一层缓冲流
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
在进行读写操作时调用缓冲流
byte[] buffer = new byte[10];
int len;
while ((len=bis.read(buffer))!=-1){
bos.write(buffer,0,len);
}
在关闭流时,应先关闭外层流,再关闭内层流
在关闭外层流的同时,内层流自动关闭,所以只需关闭外层流即可
bis.close();
bos.close();
4.2 缓冲流与节点流读写速度对比
使用缓冲流复制文件仍然可以写成一个通用的方法:
public void copyFileWithBuffered(String srcPath, String destpath)
在与节点流方式进行对比时,应保持字节读出的单位是一致的,
例如在字节流中每次读出数据的单位是1024个字节,
byte[] buffer = new byte[1024];
在缓冲流也要与其保持一致,遵循单一变量规则,这样才能体现出二者的效率
使用缓冲流进行文件复制
public void testcopyFileBuffered() {
long start = System.currentTimeMillis();
String srcPath = new String("C:\\Users\\Administrator\\Pictures\\Saved Pictures\\video2.mp4");
String destPath = new String("C:\\Users\\Administrator\\Pictures\\Saved Pictures\\video4.mp4");
copyFileWithBuffered(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("复制操作花费的时间为:" + (end - start));
}
使用字节流进行文件复制
public void testCopyFile(){
long start=System.currentTimeMillis();
String srcPath = new String("C:\\Users\\Administrator\\Pictures\\Saved Pictures\\video2.mp4");
String destPath = new String("C:\\Users\\Administrator\\Pictures\\Saved Pictures\\video3.mp4");
copyFile(srcPath,destPath) ;
long end=System.currentTimeMillis();
System.out.println("复制操作花费的时间为"+(end-start));
}
从运行结果看出,缓冲流的读写速度要快于字节流
查看BufferedInputStream的源码
这是我们调用的BufferedInputStream的构造器,在这里提供了一个DEFAULT_BUFFER_SIZE缓冲区
查看这个缓冲区
缓冲区可以存放8192个字节,在读文件时,数据先读到BufferedInputStream中,在DEFAULT_BUFFER_SIZE缓冲区中缓存,达到缓冲区的指定大小以后,一次性的写出,通过这样的一种方式提高文件的读写速度
在BufferedOutputStream中有一个flush()方法,该方法的作用是刷新当前的缓冲区,在数据放入缓冲区时,调用该方法会将数据从缓冲区中写出,在代码中不需要手动添加flush()方法,BufferedOutputStream类对象自动调用该方法
4.3 缓冲流(字符型)实现文本文件的复制
字符型缓冲流中用到的是 BufferedReader 和 BufferedWriter
public void testBufferedReaderBufferedWriter() {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(new File("eclipse常用快捷键.txt")));//使用匿名的方式创建缓冲流
bw = new BufferedWriter(new FileWriter(new File("eclipse常用快捷键1.txt")));
char[] cbuf = new char[1024];
int len;
while ((len = br.read(cbuf)) != -1) {
bw.write(cbuf, 0, len);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//关闭资源
if (br != null) {
try {
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
在进行读写操作时,除了上述常规的方法外,还多了一种处理方案,使用String的方式读写数据
String data;
while((data=br.readLine())!=null){
//换行操作 方式一
// bw.write(data+"\n");
//方式二
bw.write(data);
bw.newLine();//调用换行的方法
}
readLine()方法的含义:
包含行内容的字符串,不包括任何行终止字符,如果到达流的末尾而未读取任何字符,则为 null
按行读取数据,不包括换行符,所以需要手动添加换行操作
4.4 数据加密
在数据读入时,可以通过位运算对数据进行加密,以复制图片为例
bis = new BufferedInputStream(new FileInputStream("繁花似锦.jpg"));
bos = new BufferedOutputStream(new FileOutputStream("繁花似锦3.jpg"));
byte[] buffer = new byte[20];
int len;
while((len=bis.read(buffer))!=-1){
//对字节数据进行修改
for (int i = 0; i < len; i++) {
buffer[i]=(byte)(buffer[i]^5);
}
bos.write(buffer,0,len);
}
数据加密后图片是不能正常显示的
在这里图片被复制只是无法查看其中内容,复制后的图片大小与原图片是一致的
如果想要查看图片,再次进行位运算,将加密的图片进行解密
5. 其他IO流
5.1 转换流
- 转换流提供了在字节流和字符流之间的转换
- Java API提供了两个转换流
InputStreamReader:将InputStream转换为Reader
OutputStreamWriter:将Writer转换为OutputStream - 解码:字节、字节数组—>字符数组、字符串
编码:字符数组、字符串—>字节、字节数组 - 字节流中的数据都是字符时,转成字符流操作更高效
- 使用转换流来处理文件乱码问题。实现编码和解码的功能
将使用字节流读取文本文件的方式转换为字符流读取的方式
public void test() {
InputStreamReader isr = null;
try {
FileInputStream fis = new FileInputStream("eclipse常用快捷键.txt");
// InputStreamReader isr= new InputStreamReader(fis);//使用系统默认字符集
// 参数2指明了字符集,取决于文件保存时选用的字符集来设定
isr = new InputStreamReader(fis, "UTF-8");
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1) {
String str = new String(cbuf, 0, len);
System.out.print(str);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
在InputStreamReader转换流中可以指明字符集,取决于文件保存时选用的字符集来设定
该文本文件保存时使用的是UTF-8字符编码,所以程序中指明的字符集为UTF-8
实现文件的读入和写出
//综合使用InputStreamReader 和 OutputStreamWriter
@Test
public void test1() {
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
FileInputStream fis = new FileInputStream("eclipse常用快捷键.txt");
FileOutputStream fos = new FileOutputStream("eclipse常用快捷键2.txt");
isr = new InputStreamReader(fis, "utf-8");
osw = new OutputStreamWriter(fos, "gbk");
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1) {
osw.write(cbuf,0,len);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(isr!=null) {
try {
isr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(osw!=null)
try {
osw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
在InputStreamWriter中指定的字符编码为utf-8,字符流转换为字节流时的编码为gbk,解码与编码不一致导致文件出现乱码
两个转换流指定的字符编码需要一致才能正常显示该文本文件
5.2 标准输入、输出流
System.in和System.out分别代表了系统标准的输入和输出设备
默认输入设备:键盘,输出设备:显示器
System.in的类型是InputStream
System.out的类型是PrintStream,是OutputStream的子类FilterOutputStream的子类
重定向:通过System类的setln,setOut方法对默认设备进行改变
public static void setln(inputStream in)
public static void setOut(PrintStream out)
应用:
从键盘输入字符串,要求将读取到的整行字符串转成大写输出,然后继续进行输入操作
直至当输入“e”或者“exit"时,退出程序
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
while (true) {
System.out.println("请输入字符串:");
String data = br.readLine();
if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
System.out.println("程序结束,退出程序");
break;
}
String uppercase = data.toUpperCase();
System.out.println(uppercase);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
5.3 打印流
-
实现将基本数据类型的数据格式转化为字符串输出
-
打印流:PrintStream和PrintWriter
—>提供了一系列重载的print()和println()方法,用于多种数据类型的输出
—>PrintStream和PrintWriter的输出不会抛出IOException异常
—>PrintStream和PrintWriter有自动flush功能
—>PrintStream打印的所有字符都使用平台的默认字符编码转换为字节。
在需要写入字符而不是写入字节的情况下,应该使用PrintWriter类 —>System.out返回的是PrintStream的实例
应用:
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节‘\n’时都会刷新输出缓冲区)
ps = new PrintStream(fos, true);
if (ps != null) {
System.setOut(ps);//标准输出流输出到文件
}
for (int i = 0; i <= 255; i++) {
System.out.print((char) i);//输出Ascll码字符
if (i % 50 == 0) {
System.out.println();
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
if (ps != null)
ps.close();
}
}
将Ascll码字符输出到文件中,不在控制台显示
5.4 数据流
-
为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流
-
数据流有两个类:(用于读取和写出基本数据类型,String类的数据)
—>DataInputStream 和 DataOutputStream
—>分别”套接“在InputStream 和 OutputStream 子类的流上 -
DataInputStream中的方法
常用方法 boolean readBoolean() byte readByte() char readChar() float readFloat() double readDouble() short readShort() long readLong() int readInt() String readUTF() void readFully(byte[] b) -
DataOutputStream中的方法
—>将上述的方法的read改为相应的write即可
将数据类型写入到文件中:
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeUTF("I hava a dream");
dos.flush();
dos.writeInt(20);
dos.flush();
dos.writeBoolean(true);
dos.flush();
dos.close();
通过DataOutputStream数据流写入到文件中的内容是无法直接查看的
使用DataInputStream读取文件中的内容,并输出到控制台查看
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
String name = dis.readUTF();
int age = dis.readInt();
boolean isMale = dis.readBoolean();
System.out.println("name:"+name);
System.out.println("age:"+age);
System.out.println("isMale:"+isMale);
dis.close();
写入的顺序和读取的顺序应该是一致的,如果不一致会报错