zoukankan      html  css  js  c++  java
  • 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();
    				}
    			}
    		}
    	}
    }
    


  • 相关阅读:
    Codeforces 1255B Fridge Lockers
    Codeforces 1255A Changing Volume
    Codeforces 1255A Changing Volume
    leetcode 112. 路径总和
    leetcode 129. 求根到叶子节点数字之和
    leetcode 404. 左叶子之和
    leetcode 104. 二叉树的最大深度
    leetcode 235. 二叉搜索树的最近公共祖先
    450. Delete Node in a BST
    树的c++实现--建立一棵树
  • 原文地址:https://www.cnblogs.com/zhangmingzhao/p/7256600.html
Copyright © 2011-2022 走看看