IO流内容还是很多的,复习Java乍一看会很懵,所以写篇博文帮助自己回顾(不断更新)。
概念
按照读写数据的基本单位不同,分为 字节流 和 字符流。
- 字节流就是主要以字节为单位进行数据读写的流。一个字节是8位,计算机存储信息是以字节为度量单位。字节流可以读写任何类型的文件。
- 字符流同上,主要以字符为单位进行数据读写,一个字符由两个字节组成。只能读写文本文件。
再根据读写数据的方向不同,从程序的角度出发,可以分为输入流和输出流。
- 输入流是把数据读入程序中
- 输出流是把数据从程序中输出
代码
字节流
缓冲可以有可以没有,但是加上缓冲会加快速度。代码都默认使用缓冲
public static void main(String[] args) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
// 1.构建BufferInputStream类型对象与d:/test.mp4文件关联
bis = new BufferedInputStream(new FileInputStream("d:/test.mp4"));
// 2.构建BufferedOutputStream类型对象与d:/test_1.mp4文件关联
bos = new BufferedOutputStream(new FileOutputStream("d:/test_1.mp4"));
// 3.不断从输入流中读取数据并写入到输出流
System.out.println("正在拷贝");
byte[] bArr = new byte[1024];
int res = 0;
while ((res = bis.read(bArr)) != -1) {
bos.write(bArr, 0, res);
}
System.out.println("拷贝完成");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4.关闭流对象并释放有关的资源
try {
if (null != bos) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null != bis) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
// 1.创建BufferedReader类型的对象与d:/a.txt文件关联
br = new BufferedReader(new FileReader("d:/a.txt"));
// 2.创建BufferedWriter类型的对象与d:/b.txt文件关联
bw = new BufferedWriter(new FileWriter("d:/b.txt"));
// 3.不断地从输入流中读取一行字符串并写入到输出流中
System.out.println("正在拷贝。。。");
String str = null;
while ((str = br.readLine()) != null) {
bw.write(str);
bw.newLine();
}
System.out.println("拷贝成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4.关闭流对象并释放有关的资源
if (null != bw) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}