对包装类DataInputStream/DataOutputStream的应用

来源:互联网 发布:低空飞行淘宝 编辑:程序博客网 时间:2024/05/22 01:46

这里写图片描述

代码如下:

import java.io.*;public class DataStreamTest {    public static void main(String[] args) throws Exception {        FileOutputStream fos = new FileOutputStream("count.txt");        BufferedOutputStream bos = new BufferedOutputStream(fos);        DataOutputStream dos = new DataOutputStream(bos);        dos.writeUTF("ab中国");        dos.writeBytes("ab中国");        dos.writeChars("ab中国");        dos.close();        FileInputStream fis = new FileInputStream("count.txt");        BufferedInputStream bis = new BufferedInputStream(fis);        DataInputStream dis = new DataInputStream(bis);        System.out.println(dis.readUTF());        byte[] buf = new byte[1024];        int len = dis.read(buf);        System.out.println(new String(buf, 0, len));        fis.close();    }}

运行结果如下:
这里写图片描述

在工程中有一个count.txt文件,里面第一个“ab中国”是utf-8编码,后两个为Unicode。
writeBytes函数和writeChars函数写入的字符串很难读,我就只用了read方法先将他们读入到一个字符串数组,这样就要将之后所有的数据都读出来,这样就没有什么意义了,所以这两个方法很少使用。因为读出的是Unicode的编码,所以显示为乱码。

1 0
原创粉丝点击