Java IO2


“层层包装”


package com.demo.zmz;

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

public class DataDemo {
	public static void main(String[] args) {
		WirteData();
		ReadData();
	}
	
	private static void ReadData() {
		DataInputStream in = null;
		try {
			//包装
			in = new DataInputStream(
					new BufferedInputStream(
							new FileInputStream("person.txt")));	
			try {
				String name = in.readUTF();
				int age = in.readInt();
				boolean isSingle = in.readBoolean();
				double height = in.readDouble();
				System.out.println(name);
				System.out.println(age);
				System.out.println(isSingle);
				System.out.println(height);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (FileNotFoundException e) {
			// TODO: handle exception
		}finally {
			if(in != null) {
				try {
					in.close();
				} catch (IOException e2) {
					// TODO: handle exception
					e2.printStackTrace();
				}
			}
		}
	}
	private static void WirteData() {
		int age = 20;
		String name = "Bob";
		boolean isSingle = true;
		double height = 1.75;
		FileOutputStream fout = null;
		BufferedOutputStream bout = null;
		DataOutputStream dout = null;
		
		try {
			fout = new FileOutputStream("person.txt");
			bout = new BufferedOutputStream(fout);
			dout = new DataOutputStream(bout);
			
			//字符串
			dout.writeUTF(name);
			dout.writeInt(age);
			dout.writeBoolean(isSingle);
			dout.writeDouble(height);
			
			//强制刷新缓冲区
			dout.flush();
		} catch (FileNotFoundException e) {
			// TODO: handle exception
			e.printStackTrace();
		}catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			if(dout != null) {
				try {
					dout.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}


posted @ 2017-05-27 20:09  Lawliet__zmz  阅读(194)  评论(0编辑  收藏  举报