io不經常使用流整理

/**
 * DataInputStream和DataOutputStream
 */
public class DataStream {
	public static void main(String[] args) {
		DataOutputStream dos = null;
		DataInputStream dis = null;
		try {
			dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("f:/a.txt")));
			dis = new DataInputStream(new BufferedInputStream(new FileInputStream("f:/a.txt")));
			dos.writeDouble(Math.random());
			dos.writeBoolean(true);
			dos.writeInt(10);
			dos.writeChar('a');
			dos.writeUTF("漢語");
			dos.flush();
			System.out.println(dis.readDouble());
			System.out.println(dis.readBoolean());
			System.out.println(dis.readInt());
			System.out.println(dis.readChar());
			System.out.println(dis.readUTF());
		} catch (Exception e) {
		} finally {
			try {
				dos.close();
				dis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}


public class TestPrintStream {
	public static void main(String[] args) {
		PrintStream ps = null;
		try {
			ps = new PrintStream(new FileOutputStream(new File("f:" + File.separator + "a.txt")));
			ps.print("hi:");
			ps.println(" 你好");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			ps.close();
		}
	}
}



public static void xuLie(){
		Person person = new Person(20, true, "aa");
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		//序列化
		try {
			fos = new FileOutputStream("f:/a.txt");
			oos = new ObjectOutputStream(fos);
			oos.writeObject(person);
			oos.flush();
		} catch (Exception e) {
		}finally{
			try {
				oos.close();
				fos.close();
			} catch (IOException e) {
			}
		}
	}
	public static void reverseXuLie(){
		ObjectInputStream ois = null;
		FileInputStream fis = null;
		//反序列化
		try {
			fis = new FileInputStream("f:/a.txt");
			ois = new ObjectInputStream(fis);
			Person p = (Person) ois.readObject();
			System.out.println(p.name);
		} catch (Exception e) {
			try {
				ois.close();
				fis.close();
			} catch (IOException e1) {
			}
		}
	}

public class Person implements Serializable{
	public int age;
	public boolean isMan;
	public String name;
	public Person(int age, boolean isMan, String name) {
		this.age = age;
		this.isMan = isMan;
		this.name = name;
	}
}
相關文章
相關標籤/搜索