一、什么是io流
每当我们上传和下载某些东西时,数据的读取和存储都是以流的形式来进行操作的,流这个概念比较抽象。
流分为输入流和输出流,输入流就是将数据从磁盘读取到内存(代码中),输出流是将数据从内存中存储到磁盘中。可以以内存为参照物来理解输入和输出。
输入流又细分为字节输入流和字符输入流,输出流细分为字节输出流和字符输出流。(字符流不能处理图片、视频等,只能处理文本,因此开发多用字节流)。
二、字节输入流
代码分为六步,其中一二三步可以合起来写,代码有详细注解
import java.io.*;
public class Demo2 {
public static void main(String[] args) throws IOException {
//1.创建一个file对象的
File file = new File("文件的绝对路径");
//2.创建字节输入流的核心的类
FileInputStream fis = new FileInputStream(file);
//3.加缓冲功能(流将相当于水流。不加缓冲的话,流只有一根线一样粗细。加了缓冲后,流的粗细就可以调节,大小和你的缓冲数组有关。开发只用带缓冲的)
BufferedInputStream bis = new BufferedInputStream(fis);
// 步骤1,2,3可以合并起来写:
// BufferedInputStream bis = new BufferedInputStream(new FileInputStream("文件的
// 绝对路径"));
//4.创建一个数组 缓冲数组
byte[] buf = new byte[4 * 1024]; //4096字节
/**
* 5.读取方法
* public int read(byte[] b) 将文件中的数据 读取到缓冲数组中。在这里可能会有异
* 常,需要在方法名后添加上throws IOException
*
* 从该输入流读取最多b.length字节的数据到字节数组
*
* 读入缓冲区的总字节数,如果没有更多的数据,因为文件的结尾已经到达, -1 。
*/
int length;
while ((length = bis.read(buf)) != -1) {
//下面的String的方法为(字节数组,偏移量,读取长度)
System.out.println(new String(buf, 0, length));
}
//6.关闭(必须先开后关,后开先关)
bis.close();
fis.close();
}
}
三、字节输出流
字节流和字符流类似,也可以把前三个步骤合起来写。
import java.io.*;
public class Demo1 {
public static void main(String[] args) throws IOException {
//1.创建文件对象(文件可以不存在,会自动创建,但是地址至少要写到文件的上一级)
File file = new File("文件的绝对路径");
//2.创建核心的字节输出流对象FileOutputStream
FileOutputStream fos = new FileOutputStream(file);
//3.加缓冲的效果 BufferedOutputStream
BufferedOutputStream bos = new BufferedOutputStream(fos);
//4.声明一个字符串
String str = "abcdefgh";
/**5.写入字节
* void write(byte[] b) 将字节数组中的数据写入到
* 将 b.length个字节从指定的字节数组写入此文件输出流。
*
* void write(byte[] b, int off, int len)
* 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流。
*/
bos.write(str.getBytes(), 0, 3);
//6.关闭
bos.close();
fos.close();
}
}
四、字节流综合案例格式
public static void main(String[] args) throws IOException {
//创建缓冲输入流对象
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("文件的绝对路径"));
//创建缓冲输出流对象
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("文件的绝对路径"));
//准备一个缓冲数组
byte[] buf = new byte[4096];
int length;
while ((length = bis.read(buf)) != -1) { // 从磁盘读取数据到缓冲数组中
bos.write(buf, 0, length); //从缓冲数组中写入到磁盘
}
bos.close();
bis.close();
}
}
五、字符流
字符流步骤和字节流一模一样,只需要改一下用的类名即可,下面直接放个综合案例格式。了解了解就好。
public static void main(String[] args) throws IOException {
//字符流将一个文本赋值到另外一个文件夹下面
//BufferedReader 专门将文本内容读取到内存中
BufferedReader br = new BufferedReader(new FileReader("文本文件的绝对路径"));
BufferedWriter bw = new BufferedWriter(new FileWriter("目标文件的绝对路径"));
char[] cbuf= new char[1024];
int length;
while ((length = br.read(cbuf)) != -1) {
bw.write(cbuf, 0, length);
}
bw.close();
br.close();
}