IO流操作代码

        
    public void testBOS() throws Exception{
//        创建输出流对象
        FileOutputStream fos = new FileOutputStream("raf.txt");
//        创建缓冲字节输出流
        BufferedOutputStream bos = new BufferedOutputStream(fos);
//        所有字节先被存入缓冲区,等待一次性写出
        bos.write("select * from world where name = ?".getBytes());
//        关闭流之前,缓冲输出流会将缓冲区内容一次性写出
        bos.close();
    }
    
    
    
//    测试缓冲输入流
    public void testBIS() throws Exception{
//        创建文件输入流对象
        FileInputStream fis = new FileInputStream("raf_copy1.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
//        缓冲读取,实际上并不是一个字节一个字节的从文件中读取的
        int len = -1;
        long start = System.currentTimeMillis();
        while((len = bis.read())!=-1) {
            System.out.println(len+"");
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start+"ms");
        bis.close();
    }
    
    
    
//    基于缓冲区的文件复制
    public void testCopy() throws Exception{
        FileInputStream fis = new FileInputStream("raf.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        FileOutputStream fos = new FileOutputStream("raf_copy2.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int len;
        while((len = bis.read())!=-1){
            bos.write(len);
            System.out.println((char)len);
        }
        bis.close();
        bos.close();
    }
    
    
    
//    实现对象的序列化
    public void testOOS() throws Exception{
//        1.构建对象
        Emp emp = new Emp("张三",20,"男",5000);    
//        2.创建文件输出流FileOutputStream类对象,
//        使用该对象作为参数构造参数ObjectOutputStream
        FileOutputStream fos = new FileOutputStream("emp.obj");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
//        3.使用ObjectOutputStream的writeObject方法将Emp
//        对象写入到emp.obj文件中.
        oos.writeObject(emp);
//        4.释放资源
        System.out.println("序列化完毕");
        oos.close();
//        生成之后emp.obj中是二进制格式,无法读懂其中内容
    }
    
    
    
//    实现反序列化
    public void testOIS() throws Exception{    
        FileInputStream fls = new FileInputStream("emp.obj");
        ObjectInputStream ols = new ObjectInputStream(fls);
        Emp emp = (Emp)ols.readObject();
        System.out.println(emp);
        ols.close();
    }
    
    
    public void testOSW() throws Exception{    
        FileOutputStream fos = new FileOutputStream("osw.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
        osw.write("Mr陈");
        osw.close();
    }
    
    @Test
    public void testOSW1() throws Exception{    
        FileInputStream fos = new FileInputStream("osw.txt");
        InputStreamReader isr = new InputStreamReader(fos,"utf-8");
        int chs = -1;
        while((chs = isr.read())!=-1) {
            System.out.println((char)chs);
        }
        isr.close();
    }
}
 

猜你喜欢

转载自blog.csdn.net/CXY_ZPH/article/details/86251067