首页 > 代码库 > 处理流_缓冲流
处理流_缓冲流
1 和节点流相比,可以提升文件操作的效率
2 flush操作将最后缓存中剩余的字符串输出
package lianxi1;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import org.junit.Test;public class TestBuffered {@Test public void testCopy(){ long start = System.currentTimeMillis(); String src = "d:/io/plan.png"; String des = "prison.png"; copyFile(src,des); long end = System.currentTimeMillis(); System.out.println(end-start);} public void copyFile(String src,String des){ FileInputStream fis = null; FileOutputStream fos = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; File file1 = new File(src); File file2 = new File(des); try{ fis = new FileInputStream(file1); fos = new FileOutputStream(file2); bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); int len; byte[] b = new byte[100]; while((len=bis.read(b))!=-1){ bos.write(b, 0, len); bos.flush(); } }catch(Exception ex){ex.printStackTrace();} finally{ if(bis!=null){ try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(bos!=null){ try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}@Test public void test2(){ FileReader fr = null; FileWriter fw = null; BufferedReader br = null; BufferedWriter bw = null; File file1 = new File("d:/io/hellotext.txt"); File file2 = new File("Tangshan"); try{ fr = new FileReader(file1); fw = new FileWriter(file2); br = new BufferedReader(fr); bw = new BufferedWriter(fw);// int len;// char[] c = new char[100];// while((len=br.read(c))!=-1){// bw.write(c, 0, len);// bw.flush();// } //或用readline方法 String str; while((str=br.readLine())!=null){ bw.write(str); bw.newLine(); } }catch(Exception ex){ex.printStackTrace();} finally{ if(br!=null){ try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(bw!=null){ try { bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}}
处理流_缓冲流
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。