1 流的分类
数据单位
字节流:非文本,图片、视频等
字符流:文本
流向
输入流
输出流
角色
节点流:直接作用在文件上
处理流:在已有基础上包了一层流,例如要加快流的速度而做的流
抽象基类 | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
2 示例代码
1.FileReader读入
// 1、实例化File类对象,指明要操作的文件
// 读的时候file一定要存在,不然会报FileNotFoundException异常
// 2、提供据具体的流
// 3、数据的读入
// 4、流的关闭
@Test
public void test4() {
FileReader fr = null;
try {
// 1、实例化File类对象,指明要操作的文件
// 读的时候file一定要存在,不然会报FileNotFoundException异常
File file = new File("C:\\Users\\22370\\Desktop\\spring\\start\\src\\main\\java\\com\\ll\\aaaa.txt");
// 2、提供据具体的流
fr =new FileReader(file);
// 3、数据的读入
int data = fr.read();
while (data !=-1){
System.out.println((char) data);
data=fr.read();
}
}catch (IOException e){
e.printStackTrace();
}finally {
// 4、流的关闭
try {
if(null!=fr){
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
fr.read();一个个的读字符,效率比较低下,使用char[] buf。
// 3、数据的读入
char[] buf=new char[5];
// fr.read()返回每次读入的数组中的个数
int len = fr.read(buf);
while (len !=-1){
// 方式一
// for (int i = 0; i < len; i++) {
// System.out.print(buf[i]);
// }
// 方式二
String s=new String(buf,0,len);
System.out.print(s);
len=fr.read(buf);
}
2.缓冲流实现文件复制
File file1 = new File("C:\\Users\\22370\\Desktop\\spring\\start\\src\\main\\java\\com\\ll\\3.jpg");
File file2 = new File("C:\\Users\\22370\\Desktop\\spring\\start\\src\\main\\java\\com\\ll\\4.jpg");
FileInputStream is = null;
FileOutputStream fo=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
is = new FileInputStream(file1);
fo = new FileOutputStream(file2);
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(fo);
byte[] bytes=new byte[10];
int len = 0;
while ((len=bis.read(bytes))!=-1){
bos.write(bytes,0,len);
}