zoukankan      html  css  js  c++  java
  • Java基础-IO流对象之数据流(DataOutputStream与DataInputStream)

              Java基础-IO流对象之数据流(DataOutputStream与DataInputStream)

                                            作者:尹正杰

    版权声明:原创作品,谢绝转载!否则将追究法律责任。

    一.数据流特点

       操作基本数据类型的数据类型,若不使用数据流,写出之后会有什么结果?当然是截断啦。那有什么很好的解决方案吗?当然有啦,就是我们要说的数据流。

    二.写数据(DataOutputStream)

     1 /*
     2 @author :yinzhengjie
     3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
     4 EMAIL:y1053419035@qq.com
     5 */
     6 
     7 package cn.org.yinzhengjie.note6;
     8 
     9 import java.io.DataOutputStream;
    10 import java.io.FileOutputStream;
    11 import java.io.IOException;
    12 
    13 public class DataOutputStreamDemo {
    14     public static void main(String[] args) throws IOException {
    15         DataOutputStream dos = new DataOutputStream(new FileOutputStream("yinzhengjie.data"));
    16         
    17         //写入一个int类型的数据
    18         dos.write(97);
    19         //写入一个布尔值
    20         dos.writeBoolean(true);
    21         //写入一个字符类型
    22         dos.writeChar(97);
    23         //写入一个double类型
    24         dos.writeDouble(9.8);
    25         //写入字符串,使用的是UTF-8编码
    26         dos.writeUTF("尹正杰");
    27         
    28         //释放资源
    29         dos.close();
    30     }
    31 }

    三.读数据(DataInputStream)

     1 /*
     2 @author :yinzhengjie
     3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
     4 EMAIL:y1053419035@qq.com
     5 */
     6 
     7 package cn.org.yinzhengjie.note6;
     8 
     9 import java.io.DataInputStream;
    10 import java.io.DataOutputStream;
    11 import java.io.FileInputStream;
    12 import java.io.FileOutputStream;
    13 import java.io.IOException;
    14 
    15 public class DataOutputStreamDemo {
    16     public static void main(String[] args) throws IOException {
    17         DataInputStream dis = new DataInputStream(new FileInputStream("yinzhengjie.data"));
    18         
    19         //注意存入的顺序,读取的时候需要按照写入的顺序来读取!
    20         System.out.println(dis.read());
    21         System.out.println(dis.readBoolean());
    22         System.out.println(dis.readChar());
    23         System.out.println(dis.readDouble());
    24         System.out.println(dis.readUTF());
    25         
    26     }
    27 }
    28 
    29 /*
    30 以上代码执行结果如下:
    31 97
    32 true
    33 a
    34 9.8
    35 尹正杰
    36 */
  • 相关阅读:
    OCP-1Z0-053-200题-178题-187
    OCP-1Z0-053-200题-179题-232
    OCP-1Z0-053-200题-181题-407
    OCP-1Z0-053-200题-182题-408
    OCP-1Z0-053-V13.02-408题
    OCP-1Z0-053-200题-183题-232
    OCP-1Z0-053-200题-184题-270
    OCP-1Z0-053-200题-185题-44
    OCP-1Z0-053-200题-186题-61
    OCP-1Z0-053-200题-187题-610
  • 原文地址:https://www.cnblogs.com/yinzhengjie/p/8993274.html
Copyright © 2011-2022 走看看