day24 转换流 缓冲流

1.转换流:可操作编码表

  • java.io.outputsreamwrite
  • outputstreamwriter:字符转成字节写入文件
  • 构造方法可以加编码表(不区分大小写)默认编码表随操作系统(gbk?)
OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(
                "C:\\Users\\Desktop\\a.txt"), "utf-8");
        ow.write("张三是男人");字符,字符串,字符数组均可
        ow.close();
写和读必须编码一致
gbk中汉字两个字节
utf-8中汉字三个字节
仅关闭最外层OutputStreamWriter就一起关闭了
  • filewrite用较多,OutputStreamWriter多出功能操作编码表
  • inputstreamreader将字节转成字符到程序

2.io缓冲流 提高读写速度java.io.bufferedoutputstream

  • 均以buffered开头
  • 构造方法参数是outputstream
  • writer字节,字节数组均可
public static void main(String[] args) throws IOException {
        // 2-23375毫秒
   //      3-33501毫秒
   //      4-13672毫秒
        long a = System.currentTimeMillis();
        File in = new File("C:\\Users\\Desktop\\java\\a.zip");
        File out = new File("C:\\Users\\Desktop\\a.zip");
        text_4(in, out);
        System.out.println(System.currentTimeMillis() - a);

    }
    public static void text_4(File in, File out) throws IOException {
        BufferedInputStream bi = new BufferedInputStream(
                new FileInputStream(in));
        BufferedOutputStream bo = new BufferedOutputStream(
                new FileOutputStream(out));
        int len = 0;
        byte[] arr = new byte[1024];
        while ((len = bi.read(arr)) != -1) {
            bo.write(arr);
        }
        bi.close();
        bo.close();
    }
    public static void text_3(File in, File out) throws IOException {
        BufferedInputStream bi = new BufferedInputStream(
                new FileInputStream(in));
        BufferedOutputStream bo = new BufferedOutputStream(
                new FileOutputStream(out));
        int len = 0;
        while ((len = bi.read()) != -1) {
            bo.write(len);
        }
        bi.close();
        bo.close();
    }

    public static void text_2(File in, File out) throws IOException {
        FileInputStream fi = new FileInputStream(in);
        FileOutputStream fo = new FileOutputStream(out);
        int len = 0;
        byte[] arr = new byte[1024];
        while ((len = fi.read(arr)) != -1) {
            fo.write(arr, 0, len);

        }
        fi.close();
        fo.close();
    }

3.字符流缓存区

  • bufferwriter需要flush
  • 有特殊方法.newline换行最系统window\r\n,linux是\n
  • bufferedread
  • readline()可以直接读一行(按照换行符判断是否换行)没有之后返回null,仅会读出原本文本不会有换行符
BufferedWriter bWriter = new 
BufferedWriter(new FileWriter("C:\\Users\\Desktop\\b.txt")
                );
        BufferedReader bReader = new BufferedReader(
                new FileReader("C:\\Users\\Desktop\\a.txt"));
        String len = null;
        while ((len = bReader.readLine()) != null) {
            bWriter.write(len);
            bWriter.newLine();
            bWriter.flush();
        }
        bReader.close();
        bReader.close();

你可能感兴趣的:(day24 转换流 缓冲流)