基本数据类型处理流基础

package com.cyj.Other;

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

/**
 * 1.基本数据类型处理流
 * 输出流:DataInputStream
 * 输入流:DataOutputStream
 * 
 * 2.文件的读取和写出顺序要一致,不然类型不一样会乱码
 * @author Chyjrily
 *
 */

public class DataDealBase {

	public static void main(String[] args) throws IOException {
		
		byte[] data = write();
		 read(data);
	}
	
	/**
	 * 从字节数组中,读取数据和类型
	 * @param destPath
	 * @throws IOException 
	 */
	public static void read(byte[] src) throws IOException {
		
		//选择流
		DataInputStream dis = new DataInputStream(
			new BufferedInputStream(new ByteArrayInputStream(src))
		);
		
		//操作 读取的顺序必须与写出的顺序一致,才能肯定有文件的存在后读取
		double a = dis.readDouble();
		long b = dis.readLong();
		String str = dis.readUTF();
		
		dis.close();
		
		System.out.println("a="+a);
		System.out.println("b="+b);
		System.out.println("str="+str);
			
	}
	
	/**
	 * 保存源文件的类型和数据,到字节数组
	 * @param destPath
	 * @throws IOException
	 */
	
	public static byte[] write() throws IOException {
		
		//将文件读取到目标数组
		double a = 9.8;
		long b = 98L;  //java中定义long类型后面,L表示长整形,去掉默认是int类型,不符合规范
		String str = "中国脊梁崔永元,老痞子冯小刚";
		

		//选择流
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(
			new BufferedOutputStream(bos)
		);
		
		//操作,顺序与赋值的顺序相同,为了后面的读取顺序同步
		dos.writeDouble(a);
		dos.writeLong(b);
		dos.writeUTF(str);
		
		dos.flush();//强制刷出	
		
		//读取内容,返回值
		byte[] dest = bos.toByteArray();
		
		/**
		 * 这里特别注意,文件读取一定在关闭资源之前
		 */
		dos.close();
		return dest;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42036616/article/details/81009929
今日推荐