java常用字节流

来源:互联网 发布:ichart.1.2.min.js 编辑:程序博客网 时间:2024/04/29 12:20

常用的字节流有FileInputStream和FileOutputStream、BufferedInputStream和BufferedOutputStream、DataInputStream和DataOutputStream。

FileInputStream和FileOutputStream是基础的字节输入和输出流,通常在创建缓冲流时需要使用到,也可以用来做文件复制的功能。

 * fileInputStream和fileOutputStream字节输入输出流实现文件的复制     *     * @author:tuzongxun     * @Title: fileInAndOuTest     * @param     * @return void     * @date Jul 20, 2016 10:21:41 AM     * @throws FileNotFoundException     */    public static void fileInAndOuTest() throws IOException {        File file = new File("C:\\Users\\tuzongxun123\\Desktop\\ioTest1.txt");        // 创建一个fileInputStream对象        FileInputStream fileInputStream = new FileInputStream(file);        FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\tuzongxun123\\Desktop\\ioTest.txt"));        // 获取文件中字符的长度        int leng = fileInputStream.available();        System.out.println(leng);        for (int i = 0; i < leng; i++) {            // 读取每个字节            int in = fileInputStream.read();            System.out.print(in);            // 把读取的字节写入到另一个文件            fileOutputStream.write(in);        }        fileInputStream.close();        // 使文件立即写入到磁盘        fileOutputStream.flush();        fileOutputStream.close();    }

BufferedInputStream和BufferedOutputStream是缓冲字节输入输出流,相对于基础的字节流有更高的效率,而效率更高的原理在于用空间换取时间。
也就是说使用缓冲流的时候,会先把一定的数据放到缓冲区,也就是内存中,然后read的时候直接从缓冲区读取,这样就减少了读写磁盘文件的次数,从而减少读写时间。

/**     * BufferedInputStream和BufferedOutputStream缓冲流复制文件     *      * @author:tuzongxun     * @Title: bufferedTest     * @param @throws IOException     * @return void     * @date Jul 21, 2016 9:05:57 AM     * @throws     */    public static void bufferedTest() throws IOException {        File file = new File("C:\\Users\\tuzongxun123\\Desktop\\ioTest1.txt");        File file1 = new File("C:\\Users\\tuzongxun123\\Desktop\\ioTest2.txt");        // 缓冲输入流对象,bis和bos作为缓冲区,        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));        // 缓冲输出流对象        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file1));        //声明缓冲区大小        byte[] byte1 = new byte[1024];        while (bis.read(byte1) != -1) {            bos.write(byte1);        } ;        // 将缓冲区中的数据全部写出        bos.flush();        bis.close();        bos.close();    }

DataInputStream和DataOutputStream被称为数据输入输出流,他们因为自己的特性而常被用于网络传输,它可以保证“无论数据来自何种机器,只要使用一个DataInputStream收取这些数据,就可用本机正确的格式保存它们.“
不过现在使用spring做文件上传和下载时我自己使用的是MultipartFile,所以也就没有做DataInputStream和DataOutputStream的例子。
MultipartFile上传文件的例子可以参考:
使用springMVC实现文件上传和下载之环境配置与上传

0 0
原创粉丝点击