Java IO流总结(1)

//流总结
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();
				}
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值