IO流关系图谱
字节流
- 字节流不限于读取纯文本格式的文件,对于常见的word、Excel、PPT、MP3、MP4等音频、视频文件也是能读取的
package com.wei.io.study;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 读取操作
*/
public class ByteReadAndWriteDemo {
public static void main(String[] args) throws Exception {
String src = "C:\\IDEA\\mystudy\\file-study\\src\\main\\resources\\mytest.txt";
String dist = "C:\\IDEA\\mystudy\\file-study\\src\\main\\resources\\myOuttest.txt";
try (
// 1、方式1
FileInputStream fis = new FileInputStream(src);
// 2、方式2
//BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
//方式1
FileOutputStream fos = new FileOutputStream(dist);
//方式2
//BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dist));
) {
//长度自定义,读写速度跟硬盘有关
byte[] buffer = new byte[2048];
int len;
while ((len = fis.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, len));
// 读取到多少长度就写多少长度,避免出现乱码,避免直接使用write();
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流
- 字符流是从字节流上延伸出来为了方便对字符的读取而诞生,只能读取纯文本文件
- 常见应用场景:
- 从文本读取配置文件内容,用于程序里使用
package com.wei.io.study;
import java.io.*;
public class BufferWriteDemo {
public static void main(String[] args) throws Exception {
try (
BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\IDEA\\mystudy\\file-study\\src\\main\\resources\\mytest.txt"));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\IDEA\\mystudy\\file-study\\src\\main\\resources\\mytestWrite.txt"));
) {
// 长度自定义
char[] buffer = new char[2048];
int len;
StringBuilder builder = new StringBuilder();
while ((len = bufferedReader.read(buffer)) != -1) {
builder.append(new String(buffer,0,len));
// 读取到多少写多少
bufferedWriter.write(buffer, 0, len);
}
System.out.println(builder.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}