美文网首页
Java文件的几种读取、输出方式

Java文件的几种读取、输出方式

作者: 小明今晚加班 | 来源:发表于2019-05-20 23:01 被阅读0次

1、字节流----对文件读取(速度慢)

   /**
     * 字节流---文件的读取,输出(缺点:速度慢)
     * 
     * @throws Exception
     */
    @Test
    public void testIO1() throws Exception {
        // 输入字节流对象
        InputStream in = new FileInputStream("pkg/a.txt");
        // 输出字节流对象
        OutputStream out = new FileOutputStream("pkg/b.txt");
        //这里定义个字节数组,用来指定每次读取的字节数
        byte[] b = new byte[1024];
        int len = -1;
        while ((len = in.read(b, 0, b.length)) != -1) {
            String str = new String(b, 0, len, "UTF-8");
            System.out.println(str);
            out.write(b, 0, len);
        }
        //关闭对象
        out.close();
        in.close();
    }

2、带缓存的字节流---文件读取(速度快)

   /**
     * 缓存字节流---文件读取,输出(推荐:速度快)
     * 
     * @throws Exception
     */
    @Test
    public void testIO2() throws Exception {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("pkg/a.txt"));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("pkg/b.txt"));

        byte[] b = new byte[1024];
        int len = -1;
        while ((len = in.read(b, 0, b.length)) != -1) {
            String str = new String(b, 0, len, "UTF-8");
            System.out.println(str);
            out.write(b, 0, len);
        }
        //刷新缓冲
        out.flush();
        //关闭流对象
        in.close();
        out.close();
    }

3、字节流reader,这个方法不能指定读取的字节数(不推荐)

    /*
     * 字节流reader,不能指定字节长度读取,不建议使用
     */
    @Test
    public void testIO3() throws Exception {
        InputStreamReader in = new InputStreamReader(new FileInputStream("pkg/a.txt"), "UTF-8");
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("pkg/b.txt"));

        int len = -1;
        while ((len = in.read()) != -1) {
            System.out.println(len);
            // 写入文件
            out.write(len);
        }
        out.flush();
        in.close();
        out.close();
    }

4、带缓冲的字节流读取方式,readLine()

   /**
     * 另一种字节流读取方式----可以提供readLine()的方法,一次读取一行。
     * 
     * @throws Exception
     */
    @Test
    public void testIO4() throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("pkg/a.txt"), "UTF-8"));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("pkg/b.txt"), "UTF-8"));
        String str;
        while ((str = in.readLine()) != null) {
            System.out.println(str);
            out.write(str + "\n");
        }
        out.flush();
        in.close();
        out.close();
    }

小结:实际在用的过程,肯定是选择带有缓冲区的字节流读取方式,另外能够指定每次读取的字节数最好不过了。因此,方式2 推荐使用。

相关文章

网友评论

      本文标题:Java文件的几种读取、输出方式

      本文链接:https://www.haomeiwen.com/subject/jckrzqtx.html