您的位置:首页 > 其它

处理流_缓冲流

2014-12-11 00:10 99 查看
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();
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: