java高级语言 - I/O 流04 缓冲流

缓冲流

作用:提高流读取和写入(文件处理)的效率

处理非文本文件:

​ BufferedInputStream

​ BufferedOutputStream

​ BufferedReader

​ BufferedWriter

缓冲流复制文件

package com.io.readerwriter;

import org.junit.Test;

import java.io.*;

// test bufferStream
public class Demo06 {

    //
    @Test
    public void  BufferedStreamTest(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            // 1. create file
            File srcFile = new File("/Users/pz/Desktop/screen.png");
            File destFile = new File("/Users/pz/Desktop/screen_copy.png");
            //  2. create stream
            //  2.1 create node stream
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            //  2.2 create buffered stream
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            // 3. read and write
            byte[] buffer = new byte[10];
            int len;
            while((len = bis.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 4. close stream
            // order: close outer stream first, then close inner stream
            if(bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // inner streams closed when outer streams closed
                // fos.close();
                // fis.close();
            }
        }
    }
}

缓冲流复制文件速度

package com.io.readerwriter;

import org.junit.Test;

import java.io.*;

public class Demo07 {

    public void copyFileWithBuffered(String srcPath,String destPath){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            // 1. create file
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //  2. create stream
            //  2.1 create node stream
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            //  2.2 create buffered stream
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            // 3. read and write
            byte[] buffer = new byte[1024];
            int len;
            while((len = bis.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 4. close stream
            // order: close outer stream first, then close inner stream
            if(bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // inner streams closed when outer streams closed
                // fos.close();
                // fis.close();
            }
        }
    }
    @Test
    public void testCopyFileWithBuffered(){
        long start = System.currentTimeMillis();
        String srcPath = "/Users/pz/Desktop/study/usc_record/GMT20200323-222726_20201_inf__640x360.mp4";
        String destPath = "/Users/pz/Desktop/study/usc_record/copy.mp4";
        copyFileWithBuffered(srcPath,destPath);
        long end = System.currentTimeMillis();
        System.out.println("cost time: "+(end-start));
    }
}
// cost time: 2108
// compare with Demo5: cost 7102

处理文本文件

BufferedReader

BufferedWriter

package com.io.readerwriter;

import org.junit.Test;

import java.io.*;

// test buffered reader and buffered writer to copy text file
public class Demo08 {
    @Test
    public void testBufferedReaderBufferedWriter(){
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            // create file and stream
            br = new BufferedReader(new FileReader(new File("src/com/io/hello.txt")));
            bw = new BufferedWriter(new FileWriter(new File("src/com/io/hello_copy.txt")));

            // read and write
            // way 1
//            char[] cbuf = new char[1024];
//            int len;
//            while((len = br.read(cbuf))!=-1){
//                bw.write(cbuf,0,len);
//            }

            // way 2
            String data;
            while((data = br.readLine())!=null){
                // 1.
                //bw.write(data+"\n"); // data中不包含换行符
                // 2.
                bw.write(data);
                bw.newLine(); // 提供换行的操作
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bw!=null){
                // close stream
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
节点流(或文件流)方法缓冲流(处理流的一种)方法
FileInputStreamread(byte[] buffer)BufferedInputStreamread(byte[] buffer)
FileOutputStreamwrite(byte[] buffer,0,len)BufferedOutputStreamWrite(byte[] buffer,0,len)/flush()
FileReaderread(char[] chuff)BufferedReaderread(char[] cbuf)
FileWriterwrite(char[] chuff,0,len)BufferedWriterwrite(char[] cbuf,0,len)/flush
  1. Create file
  2. create stream
  3. read and write data
  4. close stream

练习

图片加密

hint:

int b = 0;
while((b = fis.read())!=-1){
  fos.write(b^5);
}
package com.io.readerwriter;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo09 {
    // picture encryption
    @Test
    public void test1(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("/Users/pz/Desktop/screen.png");
            fos = new FileOutputStream("/Users/pz/Desktop/screen_2.png");
            byte[] buffer = new byte[20];
            int len;
            while((len=fis.read(buffer))!=-1){
                // modify byte array
                for (int i = 0; i < len; i++) {
                    buffer[i] = (byte)(buffer[i]^5);
                }
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    // decrypt
    @Test
    public void test2(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("/Users/pz/Desktop/screen_2.png");
            fos = new FileOutputStream("/Users/pz/Desktop/screen_3.png");
            byte[] buffer = new byte[20];
            int len;
            while((len=fis.read(buffer))!=-1){
                // modify byte array
                for (int i = 0; i < len; i++) {
                    buffer[i] = (byte)(buffer[i]^5);
                }
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

获取文本上每个字符出现的次数

hint:遍历文本的每一个字符,字符及字符出现的次数保存着Map中, 将Map 中的数据写入文件

package com.io.readerwriter;

import org.junit.Test;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

// word count
// 遍历文本的每一个字符
// 字符出现的次数存在 Map中
// Map<Character,Integer> map = new HashMap<>();
// map.put('a',12);
// 把 Map 中的数据写入文件
public class Demo10 {
    @Test
    public void testWordCount(){
        FileReader fr = null;
        BufferedWriter bw = null;
        try {
            Map<Character,Integer> map = new HashMap<>();
            fr = new FileReader("src/com/io/hello.txt");

            int c = 0;
            while((c = fr.read())!=-1){
                // int back to char
                char ch = (char)c;
                if(map.get(ch)==null){
                    map.put(ch,1);
                }else{
                    map.put(ch,map.get(ch)+1);
                }
            }
            bw = new BufferedWriter(new FileWriter("src/com/io/output.txt"));
            // traversal map and write data
            Set<Map.Entry<Character,Integer>> entrySet = map.entrySet();
            for(Map.Entry<Character,Integer> entry:entrySet){
                switch (entry.getKey()){
                    case ' ':
                        bw.write("space = "+entry.getValue());
                        break;
                    case '\t':
                        bw.write("tab = "+entry.getValue());
                        break;
                    case '\r':
                        bw.write("return = "+entry.getValue());
                        break;
                    case '\n':
                        bw.write("line break = " +entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey()+"="+entry.getValue());
                        break;
                }
                bw.newLine();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr!=null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值