Java的简单理解(23)---基本数据类型处理流

Java

基本数据类型处理流

DataInputStream
DataOutputStream

1. 写到字节数组中
/**
* 数据+文件输出字节数组中
*/
public byte[] write() {

   double point = 2.5;
   long num = 100L;
   String str = "数据类型";

   byte[] dest = null;

   // 创建源
   ByteArrayOutputStream bos = new ByteArrayOutputStream();

   // 选择流  DataOutputStream
   try {
       DataOutputStream os = new DataOutputStream(new BufferedOutputStream(bos));

       // 操作 写出的顺序 为读取准备
       os.writeDouble(point);
       os.writeLong(num);
       os.writeUTF(str);

       os.flush();

       dest = bos.toByteArray();

       // 释放资源
       os.close();


   } catch (FileNotFoundException e) {
       e.printStackTrace();
   } catch (IOException e) {
       e.printStackTrace();
   }
   return dest;
}
2. 从字节数组中读取出
/**
 * 从字节数组读取数据+类型
 */
public void read() {

    // 源文件
    byte[] dest = write();

    // 选择流 DataInputStream
    try {
        DataInputStream is = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(dest)));

        // 操作 读取的顺序与写出的一致 必须存在才能读取
        double num1 = is.readDouble();
        long num2 = is.readLong();
        String str = is.readUTF();

        // 释放资源
        is.close();

        System.out.println(num1);
        System.out.println(num2);
        System.out.println(str);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、IO流 1.1、概述 之前学习的File类它只能操作文件或文件夹,并不能去操作文件中的数据。真正保存数据的是文...
    Villain丶Cc阅读 2,708评论 0 5
  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,101评论 2 89
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,317评论 6 13
  • 有一天,我把所有记忆都烧掉,从此我的步伐就变轻盈啦 当我得知那件事,我突然明白之前啊,我所有的不安猜测疑问都有了答...
    自己找鱼的喵喵阅读 178评论 0 0
  • 姓名:肖作洋 2018年4月20 宁波市百雷仕电动工具有限公司 【日精进打卡第2天】 感谢一组 【知~学习】 《六...
    风车车_4da6阅读 221评论 0 0