最近在学习Java,所以就总结一篇文件字节流和字符流的输入和输出。
总的来说,IO流分类如下:
输入输出方向: 输入流(从外设读取到内存)和输出流(从内存输出到外设)
数据的操作方式: 字节流和字符流
其中,字符流的由来:字节流读取文字字节数据后,不直接操作,而是先查指定的编码表(为什么是指定的?因为不同的国家制定的编码表不一样)获取对应的文字,再对这个文字进行操作。简单说:字符流=字节流+编码表
字节流和字符流的区别:字节流不仅可以操作字符,还可以操作其他媒体文件
来张形象的图片:
Java中的顶层父类:
字节流:
InputStream,OutputStream
字符流:
Reader, Writer
缓存技术
使用缓存技术能提高性能(?为什么,因为缓存技术相当于实在内存中开辟一个容器,将外设中的数据放到容器中,然后对容器进行操作,相比直接操作外设,确实大大提高效率)
1.自己定义缓存区:相当于自定义一个数组
字节流缓存区:byte[] buf = new byte[1024];
字符流缓存区:char[] buf = new char[1024];
2.利用缓存类,此处用到了装配设计模式
何为装配设计模式?
当需要对对象进行功能扩展时,为了避免继承的臃肿和不灵活,将装配类进行单独的封装,那个对象需要就将哪个对象和装配类进行关联
字节流缓存:BufferedInputStream bfi = new BufferedInputStream(fi);
BufferedOutputStream bfo = new BufferedOutputStream(fo);
字符流缓存 :BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);
示例:
1.使用字符流赋值一个txt文件
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class BufferedRWDemo { public static void main(String[] args) throws Exception { // 读写相结合
FileReader fr = new FileReader("fw.txt"); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter("fwcopy.txt"); BufferedWriter bw = new BufferedWriter(fw); String line = null; while((line=br.readLine())!=null) { bw.write(line); bw.newLine();//此处不写就没有换行
bw.flush(); System.out.println(new String(line)); } br.close(); bw.close(); } }
2.使用字节流复制一个图片文件
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class IOStreamDemo { public static void main(String[] args) throws IOException { // 用字节流复制一个图片文件 //copy_1();
copy_2(); } private static void copy_2() throws IOException { // 利用装配模式,加入缓冲技术
FileInputStream fi = new FileInputStream("miao.jpg"); //定义缓冲对象
BufferedInputStream bfi = new BufferedInputStream(fi); FileOutputStream fo = new FileOutputStream("miao_copy_1.jpg"); BufferedOutputStream bfo = new BufferedOutputStream(fo); int len = 0; while((len= bfi.read())!=-1) { bfo.write(len); } bfo.flush(); bfi.close(); bfo.close(); } private static void copy_1() throws IOException { FileInputStream fi = new FileInputStream("miao.jpg"); FileOutputStream fo = new FileOutputStream("miao_copy.jpg"); //自定义缓冲区
byte[] buf = new byte[1024];//注意:此处是byte数组
int len = 0; while((len=fi.read(buf))!=-1) { fo.write(buf, 0, len); } fi.close(); fo.close();//注意:如果不关闭资源,copy的图片文件在打开时就会出问题
} }
末尾来一张美景放松一下,话说我们不仅要每天都有进步,还要有发现美的眼睛。