BufferedInputStream
和BufferedOutputStream
分别使用内部字节数组(也称为缓冲区)来存储读写数据。 缓冲流通常比类似的非缓冲流更有效。
下面是一个演示如何使用BufferedInputStream
的示例。
文件:BufferedInputStreamExample.java –
package com.yiibai.tutorial.io; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * @author yiibai BufferedInputStreamExample.java Nov 5 2016 */ public class BufferedInputStreamExample { public static void main(String[] args) { File file = new File("file.txt"); FileInputStream fileInputStream = null; BufferedInputStream bufferedInputStream = null; try { fileInputStream = new FileInputStream(file); bufferedInputStream = new BufferedInputStream(fileInputStream); // Create buffer byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = bufferedInputStream.read(buffer)) != -1) { System.out.println(new String(buffer 0 bytesRead)); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileInputStream != null) { fileInputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
执行上面示例代码,得到以下结果:
This is an example of reading data from file using BufferedInputStream.
以下是BufferedOutputStream
的演示示例。
文件:BufferedOutputStreamExample.java –
package com.yiibai.tutorial.io; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * @author yiibai * BufferedOutputStreamExample.java * Nov 5, 2016 */ public class BufferedOutputStreamExample { public static void main(String[] args) { File file=new File("outfile.txt"); FileOutputStream fileOutputStream=null; BufferedOutputStream bufferedOutputStream=null; try { fileOutputStream=new FileOutputStream(file); bufferedOutputStream=new BufferedOutputStream(fileOutputStream); bufferedOutputStream.write("This is an example of writing data to a file".getBytes()); bufferedOutputStream.write(" using BufferedOutputStream".getBytes()); bufferedOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); }finally { try { if(fileOutputStream!=null){ fileOutputStream.close(); } if(bufferedOutputStream!=null){ bufferedOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
执行上面示例代码,得到以下结果:
This is an example of writing data to a file using BufferedOutputStream
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264112.html