标签:target 通过 color img 缓冲区 src comm ring 资源
IO 的分类可以为:
按流操作的数据类型可以分为:字节流 、 字符流
按流的数据方向:输入流、输出流 等
InputStream
有read
方法,一次读取一个字节,OutputStream
的write
方法一次写一个int
。这两个类都是抽象类。意味着不能创建对象,那么需要找到具体的子类来使用。操作流的步骤都是:File file = new File("d:/a.txt"); InputStream inputStream = new FileInputStream(file); int length = 0; while ((length = inputStream.read())!=-1) { System.out.print((char)length); }
案例二:使用read 读取一个字节数组,提高效率
File file = new File("d:/a.txt"); InputStream inputStream = new FileInputStream(file); byte[] buf = new byte[1024]; int length = 0; length = inputStream.read(buf); for(int i=0;i<length;i++){ System.out.print((char)buf[i]); }
案例三:read 使用字节数组缓存,提高效率
FileInputStream fis = new FileInputStream(path); byte[] byt = new byte[1024]; int len = 0; while ((len = fis.read(byt)) != -1) { System.out.println(new String(byt, 0, len)); } fis.close();
OutputStram
的write
方法,一次只能写一个字节。成功的向文件中写入了内容。但是并不高效,如何提高效率呢?可以使用缓冲,OutputStram
类中有write(byte[] b)
方法,将 b.length
个字节从指定的 byte
数组写入此输出流中File file = new File("d:/a.txt"); OutputStream outputStream = new FileOutputStream(file); outputStream.write(‘a‘); outputStream.write(‘+‘); outputStream.write(‘b‘); outputStream.write(‘=‘); outputStream.write(‘c‘); outputStream.close();
案例五: write 写一个 byte 数组
File file = new File("d:/a.txt"); OutputStream outputStream = new FileOutputStream(file); byte[] buf = "a+b = c".getBytes(); outputStream.write(buf); outputStream.close();
案例六:实现文件的拷贝
InputStream inputStream = new FileInputStream("d:/a.txt"); OutputStream outputStream = new FileOutputStream("d:/b.txt"); byte[] buf = new byte[1024]; int size = 0; while ((size=inputStream.read(buf))!=-1){ outputStream.write(buf,0,size); } inputStream.close(); outputStream.close();
缓冲流
BufferedInputStream
和 BufferedOutputStream。BufferedOutputStream
和BufferedOutputStream
类可以通过减少读写次数来提高输入和输出的速度。它们内部有一个缓冲区,用来提高处理效率。查看API文档,发现可以指定缓冲区的大小。其实内部也是封装了字节数组。没有指定缓冲区大小,默认的字节是8192。显然缓冲区输入流和缓冲区输出流要配合使用。首先缓冲区输入流会将读取到的数据读入缓冲区,当缓冲区满时,或者调用flush
方法,缓冲输出流会将数据写出。InputStream inputStream = new FileInputStream("d:/a.txt"); OutputStream outputStream = new FileOutputStream("d:/b.txt"); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); int size = 0; while ((size=bufferedInputStream.read())!=-1){ bufferedOutputStream.write(size); } bufferedInputStream.close(); bufferedOutputStream.close(); inputStream.close(); outputStream.close();
标签:target 通过 color img 缓冲区 src comm ring 资源
原文地址:https://www.cnblogs.com/baizhuang/p/12149652.html