//流总结
package com.test.io;
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;
/**
* 处理流的使用
* 节点流(4个): 处理流
* FileInputStream BufferedInputStream (flush())
* FileOutputStream BufferedOutputStream (flush())
* FileReader BufferedReader (flush()) readLine 读一行
* FileWriter BufferedWriter (flush())
* @author mxr
* 处理流是升级得到的
*/
public class BufferStream {
public void testReader(){
File file = new File("H:/javatext/aa.txt");
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(new File("H:/javatext/nn.txt")));
String str;//结尾不等于空
while((str = br.readLine())!=null){
// System.out.println(str);
bw.write(str);
bw.newLine(); //重新起一行
bw.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw!=null){
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(br!=null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Test
//缓存流的非文本文件的复制
public void test(){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
File src = new File("H:/javatext/111.doc");
File dest = new File("H:/javatext/22.doc");
//2.创建响应的节点流,FileInputStream,FileOutputStream
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(dest));
//实现文件的复制
int len;
byte[] b = new byte[1024];//lKB=1024B
while((len = bis.read(b))!=-1){
bos.write(b, 0, len);
//BufferedOutputStream阻塞式的所以需要刷新
bos.flush();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关缓冲流就可以了,他会自动关闭牛节点流
if(bos != null){
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(bos != null){
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}