java常用类解析三:IO系统装饰类

java IO系统采用装饰器模式,用一些装饰类来装饰输入输出来,提供更强大的IO操作

FilterInputStream(FilterOutputStream)继承自InputStream(Outputstream)

常用装饰类(都继承自FilterInputStream)               功能

DataInputStream(DataOutputStream)                 读写基本类型即UTF

BufferedInputStream(BufferedOutputStream)      使用缓冲区

PrintStream继承自Outputstream,用于格式化输出到文本或控制台等

 

示例:

package test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * DataInputStream继承自FilterInputStream(FilterInputStream继承自InputStream)
 * 用来装饰InputStream,提供可移植方式从流读取基本数据类型
 * DataOutputStream继承自FilterOutputStream(FilterOutputStream继承自OutputStream)
 * 用来装饰OutputStream,提供可移植方式向流写入基本数据类型
 * DataInputStream/DataOutputStream可以实现数据的存储与恢复
 */
public class DataInputStreamDemo {
	public static void main(String[] args) {
		DataOutputStream dataOutStream = null;
		try {
			dataOutStream = new DataOutputStream(new BufferedOutputStream(
					new FileOutputStream("file/aa.data")));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {// 写入文件
			dataOutStream.writeChar('a');
			dataOutStream.writeInt(3);
			dataOutStream.writeDouble(5.5);
			dataOutStream.writeFloat(3.2f);
			dataOutStream.writeUTF("nihaoma");
			dataOutStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		DataInputStream dataInputStream = null;
		try {
			dataInputStream = new DataInputStream(new BufferedInputStream(
					new FileInputStream("file/aa.data")));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		try {// 读取文件
			System.out.println(dataInputStream.readChar());
			System.out.println(dataInputStream.readInt());
			System.out.println(dataInputStream.readDouble());
			System.out.println(dataInputStream.readFloat());
			System.out.println(dataInputStream.readUTF());
			dataInputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


 

package test;

import java.io.FileNotFoundException;
import java.io.PrintStream;

/*
 * 继承自FilterOutputStream,其中DataOutputStream处理数据的存储,PrintStream处理显示
 * 用于格式化打印
 */
public class PrintStreamDemo {
	public static void main(String[] args) throws FileNotFoundException {
		// 把数据可视化格式显示到文本文件中
		PrintStream printStream = new PrintStream("file/test2.txt");
		printStream.println('a');
		printStream.println(2);
		printStream.println(3.2);
		printStream.println("liuhaifang");
		printStream.println("刘海房");
		// 可视化显示到控制台
		printStream = new PrintStream(System.out);
		printStream.println("hello  java");
	}
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值