数据流DataInputStream和内存流ByteArrayInputStream

来源:互联网 发布:马云 大数据 贵州 编辑:程序博客网 时间:2024/06/08 11:17

数据输入流和数据输出流
提供了各种方法方便数据的输入和输出

public static void main(String[] args) throws IOException    {        writeData();        readData();    }    public static void readData()throws IOException    {        DataInputStream dis =new DataInputStream(new FileInputStream("data.txt"));        System.out.println(dis.readDouble());        System.out.println(dis.readBoolean());        System.out.println(dis.readChar());        dis.close();    }    public static void writeData()throws IOException    {        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));        dos.writeDouble(66.78);        dos.writeBoolean(false);        dos.writeChar('k');        dos.close();    }

内存输入流和内存输出流
内存输入流把内存中的数据存入缓冲区

public static void main(String[] args) throws IOException    {        //内存流:        //ByteArrayInputStream:从内存中读,                               //ByteArrayInputStream(byte[] buf)//从字节数组中读         //ByteArrayOutputStream:向内存中写                               //内部有一个字节数组,数据被写到该数组中        byte[] arr = "hello,大家好!".getBytes();        ByteArrayInputStream bis = new ByteArrayInputStream(arr);        ByteArrayOutputStream bos = new ByteArrayOutputStream();        byte[] a = new byte[1024];        int len = 0;        while((len = bis.read(a))!=-1)        {            bos.write(a,0,len);        }        //得到ByteArrayOutputStream对象内部数组中的数据        //将对象内部数组中的数据写入data        byte[] data = bos.toByteArray();        System.out.println(new String(data));    }
0 0