DataInputStream和DataOutputStream

package stream.data;

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 DataOutputStream
 * 
 * @author 半步疯子
 * 
 * 可用于密码的输入输出:
 * 	因为是跳过操作系统,直接操作的是java中的基本数据类型
 * 	所以必须要知道读取的顺序,才能解析出正确的编码答案
 */
public class DataStreamDemo {
	// input 和 output 都为对应的inputStream和outputStream的包装类
	public static void main(String[] args) throws IOException {
		write();
		read();
		
		writeUtf();
	}
	private static void writeUtf() {
		DataOutputStream dos = null;
		try {
			dos = new DataOutputStream(new FileOutputStream("data.txt"));
			dos.writeByte(32);
			dos.writeInt(-97);
			
			// dos.writeUTF("abc");
			// dos.writeUTF("中国");

			dos.writeChars("abc");
			dos.writeChars("中国");
			
			System.out.println("写文件操作完成");
					
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {			
			e.printStackTrace();
		}finally {
			if(dos != null) {
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	// 创建数据输入流,完成将写入到dos.txt中的数据读出来
	private static void read() throws IOException {
		DataInputStream dis = new DataInputStream(new FileInputStream("dos.txt"));
		
		byte a = dis.readByte();
		short b = dis.readShort();
		int c = dis.readInt();
		long d = dis.readLong();
		float e = dis.readFloat();
		double f = dis.readDouble();
		char g = dis.readChar();
		boolean h = dis.readBoolean();
	
		System.out.println(a);
		System.out.println(b);
		System.out.println(c);
		System.out.println(d);
		System.out.println(e);
		System.out.println(f);
		System.out.println(g);
		System.out.println(h);
		
		
		dis.close();
	}

	/*
	 * 创建数据输出流对象,并完成写文件到dos.txt中的动作
	 */
	private static void write() throws IOException {
		DataOutputStream dos = new DataOutputStream(new FileOutputStream("dos.txt"));
		dos.writeByte(10);
		dos.writeShort(100);
		dos.writeInt(1000);
		dos.writeLong(10000);
		dos.writeFloat(12.34F);
		dos.writeDouble(12.56);
		dos.writeChar('a');
		dos.writeBoolean(true);
		
		dos.close();
	}
	
	
}


posted @ 2018-05-18 21:12  五彩世界  阅读(121)  评论(0编辑  收藏  举报