java IO流 之 字节流与字符流

时间:2019-08-27
本文章向大家介绍java IO流 之 字节流与字符流,主要包括java IO流 之 字节流与字符流使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

其实学习了file文件基础类,后面的字节流和字符流都特别简单了,首先需要知道字节流和字符流的区别

字节流:

  用来传送图片、各种文件、大文件、文本都是通过字节流进行传输的。

字符流: 

  只能读取文本信息

字节流操作接口类

  1、InputStream  字节输入流

  2、outputStream 字节输出流

  3、FileinputStream 实例化字节输入流

  4、FileoutputStream 实例化字节输出流

  5、BufferedInputStream 加强版输入流,用于大文件传输时输入缓存

  6、BufferedOutputStream 加强版输出流,用于大文件传输时输出缓存

    /**
     * 文件copy 加强版(用的最多的) 几个G的文件也就10几秒
     * 
     * @param file 传入文件的路径
     * @return
     */
    public static boolean Read(File file) {

        // File file = new File("D:\\1.txt");

        if (file == null || file.isFile()) {
            System.err.println("文件不能为空");
            return false;
        }

        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file)); // 获取文件流
            bos = new BufferedOutputStream(
                    new FileOutputStream("D:\\video\\AdminVideo\\PrivateVideo\\" + file.getName())); // 转存为...

            int len = 0;
            byte[] b = new byte[1024000];
            while (-1 < (len = bis.read(b))) {
                bos.write(b, 0, len);
            }
            bos.flush();
            System.err.println("D:\\video\\AdminVideo\\PrivateVideo\\" + file.getName());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                bos.close();
                bis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 字符流  循环读取文本
     * @throws IOException
     */
    public static void file2() throws IOException {
        // 定义文件路径
        File f = new File("d:" + File.pathSeparator + "test.txt");
        //  定义字符输出流
        Reader reader = new FileReader(f);
        int len = 0;
        char[] c = new char[1024];
        int temp = 0;
        // 通过循环方式读取文件中的字符
        while ((temp = reader.read()) != -1) {
            c[len] = (char) temp;
            len++;
        }
        // 关闭字符流,不然会报错
        reader.close();
        System.out.println("内容为:" + new String(c, 0, len));
    }

实例非常简单,希望对你的学习有所帮助。又不懂得可以在评论区留言,我会尽快给您回复的

原文地址:https://www.cnblogs.com/yonim/p/9477762.html