Java中IO流的对象流和字节流的转换

一、对象流

1.对象流–借助于字节流

 @Test//对象流--借助于字节流
    public void test2() throws Exception {
    
    
        //1.将java对象写入文本中保存--序列化
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/a.jpg"));
        oos.writeObject(new Monkey("狒狒"));

        //2.将文本中保存的对象读取到程序中--反序列化
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/a.jpg"));
        Monkey m=(Monkey)ois.readObject();
        System.out.println(m);
    }

在这里插入图片描述

二、字节流的转换

1.字节流转换成字符流和缓冲流

代码如下(示例):

@Test
    public void test1() throws Exception {
    
    
        //字节流-->字符流的转换
        Reader ir = new InputStreamReader(new FileInputStream("src/a.txt"));
        //转换字符缓冲流
        BufferedReader br = new BufferedReader(ir);
        br.readLine();
    }

总结

以上就是对象流和字符流转换的相关内容,主要实现了流和对象之间和结合。

猜你喜欢

转载自blog.csdn.net/StruggleBamboo/article/details/112001921