Java中IO之BIO

 BIO实际为最原始的io,在java.io包下面,可以理解为Block-io(阻塞io),也可以理解为Base-io(基础io);

bio的分类分为:

1、输入流和输出流;

2、字节流和字符流和缓冲流

字节流 --》inputStream / OutputStream ----( 实现类 )FileInputStream / FileOutInputSream

字符流 --》Reader / Writer ----( 实现类 )FileReader / FileWriter

缓冲流 --》BufferReader / BufferWriter

c3425adf0b457b40ca6689fc778f833870d.jpg

BIO使用的举例:

字节流实现

	/**
	 * 字节流文件复制
	 * @param f 源文件
	 * @param f1 目的文件 
	 * @throws IOException
	 */
	public static void copyByByte(File f, File f1) throws IOException{
		//输入字节流
		InputStream input = new FileInputStream(f);
		//输出字节流
		OutputStream output = new FileOutputStream(f1,true);
		
		//一个字节数组
		byte[] bt = new byte[1024];
		int count = input.read(bt);
		//文件读取完标志
		while(count != -1){
		String str = new String(bt, 0, count);
		System.out.println(str);
		output.write(bt);
		count = input.read(bt);
		}
 
		//先关闭输出流,再关闭输入流
		output.flush();
		output.close();
		input.close();
	}

字符流实现

/**
	 * 字符流文件复制
	 * @param f 源文件
	 * @param f1 目的文件 
	 * @throws IOException
	 */
	public static void copyByChar(File f, File f1) throws IOException{
		//输入字符流
		Reader reader = new FileReader(f);
		//输出字符流
		Writer writer = new FileWriter(f1);
		
		//一个字符数组
		char ch[] = new char[1024];
		int count = reader.read(ch);
		while(count != -1){
		String str = new String(ch, 0, count);
		System.out.println(str);
		writer.write(ch);
		count = reader.read(ch);
		}
		
		//先关闭输出流,再关闭输入流
		writer.flush();
		writer.close();
		reader.close();
	}

缓冲流实现

/**
	 * 缓冲流文件复制
	 * @param f 源文件
	 * @param f1 目的文件 
	 * @throws IOException
	 */
	public static void copyByBuffer(File f, File f1) throws IOException{
		Reader reader = new FileReader(f);
		Writer writer = new FileWriter(f1,true);
		//字符流包装成缓冲流
		BufferedReader br = new BufferedReader(reader);
		PrintWriter pw = new PrintWriter(writer,true);
 
		//读取一行
		String str = br.readLine();
		while(str != null){
		System.out.println(str+"\r\n");
		pw.write(str.trim());
		str = br.readLine();
		}
		
		//先关闭输出流,再关闭输入流
		pw.flush();
		pw.close();
		br.close();
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值