Java基础巩固系列 数据流

代码示例: 

    @Test
    public void testData1() {
        DataInputStream dis = null;
        try {
            dis = new DataInputStream(new FileInputStream(new File("data.txt")));
//            byte[] b = new byte[20];  //这种方法会有乱码
//            int len;
//            while ((len = dis.read(b)) != -1) {
//                System.out.print(new String(b, 0, len));
//            }
            String str = dis.readUTF();
            System.out.println(str);
            boolean b = dis.readBoolean();
            System.out.println(b);
            long l = dis.readLong();
            System.out.println(l);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //数据流:用来处理基本数据类型、String、字节数组的数据:DataInputStream  DataOutputStream
    @Test
    public void testData() {
        DataOutputStream dos = null;
        try {
            FileOutputStream fos = new FileOutputStream("data.txt");
            dos = new DataOutputStream(fos);

            dos.writeUTF("我好累,你却不知道!");
            dos.writeBoolean(true);
            dos.writeLong(13415145153L);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

猜你喜欢

转载自blog.csdn.net/Peter__Li/article/details/89049265