java学习笔记 IO学习笔记2 IO流-字节流

IO流从功能上可以分为:输入流和输出流。

从结构上可以分为:1)字节流:使用接口InputStream和OutputStream

                                    2)字符流:使用接口Reader和Writer 。 字符流,底层也是字节流来是实现。


读数据流的逻辑:open a stream ->while more information -> read information ->close information

写数据流的逻辑:open a stream ->while more information -> write information ->close information

一般输入输出的写法:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class IOStreamTest {
	
	public static void main(String[] args) throws Exception {
		
		InputStream is = new FileInputStream(new File("c:" +File.separator+"Test.txt"));
		
		byte[] buffer = new byte[2048];
	
		int length = 0;
		// 当读出的数据长度为-1时候,表示数据已经读完了
		while(-1!=(length= is.read(buffer, 0, buffer.length))){
			
			String str = new String(buffer,0,length);
			// 打印出每一行数据
			System.out.print(str);
			
		}
        // 关闭输入流
		is.close();
	}
}
输出文件:

                OutputStream os = new FileOutputStream(new File("hello.txt"));
		
		String str = "this is hello world!!";
		
		byte[] buffer1 = str.getBytes();
		
		os.write(buffer1);
		
		os.close();

字节流内分为 节点流和过滤流

节点流:是从特定的地方读取写入的流类,都直接实现了inputStream 和 outputStream

过滤流:是使用节点流作为输入输出的流类。常用的是以FilterInputStream和FilterOutputStram为父类的。而两者也是继承自inputStream 和 outputStream

也就是说过滤流无法直接与输入输出打交道,他只能通过包装节点流,对输入输出进行相关操作。

输入---节点流---过滤流--过滤流--节点流-输出

这里就用到java中的另外一种设计模式。装饰模式(Decorator)将在下一篇介绍,可以通过动态的方式扩展对象的功能。

例如:

               // 用BufferedOutputStream包转节点流FileOutputStream
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("hello world.txt"));
		
		bos.write("hello world!!".getBytes());
		bos.write("123456789!".getBytes());
		// 流关闭前,数据不会写入文件中
		bos.close();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值