JavaIO流03:缓冲流、转换流、标准输入输出流、打印流、数据流

本文详细介绍了Java中的IO流,包括缓冲流提升读写效率的原理,缓冲流课后的图片加密解密练习,转换流在字节流与字符流间转换的作用,特别是字符集的概念,以及标准输入输出流、打印流和数据流的基本使用和特点。
摘要由CSDN通过智能技术生成

一、缓冲流

BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter

  • 作用:提高流的读取、写入的速度
  • 提高读写速度的原因:内部提供了一个缓冲区
  • 处理流,就是”套接“在已有的流的基础上
public class BufferedTest {
    /*
    实现非文本文件的复制
     */
    @Test
    public void BufferedStreamTest() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.造文件
            File srcFile = new File("2022.06.25.jpg");
            File destFile = new File("2022.06.25-1.jpg");
            //2.造流
            //2.1 造节点流
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            //2.2 造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //3.复制的细节:读取、写入
            byte[] buffer = new byte[10];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);

//                bos.flush(); //刷新缓冲区
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源关闭
            //要求:先关闭外层的流,再关闭内层的流。
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //说明:关闭外层流的同时,内层流也会自动的进行关闭。所以内层流的关闭可以省略。
//        fos.close();
//        fis.close();
        }
    }

    //实现文件复制的方法
    public void copyFileWithBuffered(String srcPath, String destPath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.造文件
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2.造流
            //2.1 造节点流
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            //2.2 造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //3.复制的细节:读取、写入
            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.资源关闭
            //要求:先关闭外层的流,再关闭内层的流。
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void testCopyFileWithBuffered() {
        long start = System.currentTimeMillis();

        String srcPath = "";
        String destPath = "";

        copyFileWithBuffered(srcPath, destPath);

        long end = System.currentTimeMillis();

        System.out.println("复制操作发话的时间为:" + (end - start));
    }

    /*
    使用BufferedReader和BufferedWriter实现文本文件的复制
     */
    @Test
    public void testBuffereReaderBufferedWriter() {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //1.创建文件和相应的流
            br = new BufferedReader(new FileReader(new File("hello.txt")));
            bw = new BufferedWriter(new FileWriter(new File("hello3.txt")));

            //2.读写操作
            //方式一:
//            char[] cbuf = new char[1024];
//            int len;
//            while ((len = br.read(cbuf)) != -1) {
//                bw.write(cbuf, 0, len);
//            }
            //方式二:使用String
            String data;
            while ((data = br.readLine()) != null) {
                //方法一:
//                bw.write(data + "\n"); //data中不包含换行符
                //方法二:
                bw.write(data); //data中不包含换行符
                bw.newLine(); //提供换行的操作
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3.关闭资源
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

二、缓冲流课后练习

实现图片的加密、解密操作
public class PicTest {

    //图片的加密
    @Test
    public void test1() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("2022.06.25.jpg");
            fos = new FileOutputStream("2022.06.25-secret.jpg");

            byte[] buffer = new byte[20];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                //对字节数据进行修改
                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();
                }
            }
        }
    }

    //图片的解密
    @Test
    public void test2() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("2022.06.25-secret.jpg");
            fos = new FileOutputStream("2022.06.25-2.jpg");

            byte[] buffer = new byte[20];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                //对字节数据进行修改
                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();
                }
            }
        }
    }
}

获取文本文件中每个字符出现的次数(运行时报错,未修正

/*
练习:获取文本上字符出现的次数,把数据写入文件

思路:
1.遍历文本的每一个字符
2.字符出现的次数存在Map中
 */

public abstract class WordCount {

    @Test
    public void testWordCount() {
        FileReader fr = null;
        BufferedWriter bw = null;
        try {
            //1.创建Map集合
            Map<Character, Integer> map = new HashMap<>();

            //2.遍历每一个字符,将每一个字符出现的次数放到map中
            fr = new FileReader("hello.txt");
            int c = 0;
            while ((c = fr.read()) != -1) {
                //int 还原 char
                char ch = (char) c;
                //判断char是否在map中第一个出现
                if (map.get(ch) == null) {
                    map.put(ch, 1);
                }else {
                    map.put(ch, map.get(ch) + 1);
                }
            }

            //3.把map中的数据存到文件wordcount.txt
            //3.1 创建Writer
            bw = new BufferedWriter(new FileWriter("wordcount.txt"));

            //3.2 遍历mao,再写入数据
            Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
            for (Map.Entry<Character, Integer> entry : entrySet) {
                switch (entry.getKey()) {
                    case ' ':
                        bw.write("空格=" + entry.getValue());
                        break;
                    case '\t': //\t表示 tab 键字符
                        bw.write("tab键=" + entry.getValue());
                        break;
                    case '\r': //\r表示回车键字符
                        bw.write("回车=" + entry.getValue());
                        break;
                    case '\n': //\n表示换行
                        bw.write("换行键=" + entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey() + "=" + entry.getValue());
                        break;
                }
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关流
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

三、转换流

  • 作用:转换流提供了在字节流和字符流之间的转换
  • Java API 提供了两个转换流:(属于字符流)
    • InputStreamReader:将 InputStream (字节的输入流) 转换为 Reader(字符的输入流)
    • OutputStreamWriter:将 Writer(字符的输出流) 转换为 OutputStream(字节的输出流)
  • 字节流中的数据都是字符时,转成字符流操作更高效。
  • 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。
    • 解码:字节、字节数组 —> 字符数组、字符串
    • 编码:字符数组、字符串 —> 字节、字节数组
/*
1.转换流:属于字符流
    InputStreamReader
    OutputStreamWriter
 */
public class InputStreamReaderTest {
    /*
    InputStreamReader:实现字节的输入流 --> 字符的输入流的转换
     */
    @Test
    public void test1() {

        InputStreamReader isr = null; //使用系统默认的字符集
        try {
            FileInputStream fis = new FileInputStream("hello.txt");
            isr = new InputStreamReader(fis);
            //使用自定义的字符集,具体使用哪个字符集取决于文件 hello.txt 保存时使用的字符集
//        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");

            char[] cbuf = new char[20];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                String str = new String(cbuf, 0, len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
    综合使用InputStreamReader和OutputStreamWriter
     */
    @Test
    public void test2() {

        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            //造文件、造流
            File file1 = new File("hello.txt");
            File file2 = new File("hello-gbk.txt");

            FileInputStream fis = new FileInputStream(file1);
            FileOutputStream fos = new FileOutputStream(file2);

            isr = new InputStreamReader(fis, "utf-8");
            osw = new OutputStreamWriter(fos, "gbk");

            //读写过程
            char[] cbuf = new char[20];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                osw.write(cbuf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
字符集

常见的编码表
ASCII:美国标准信息交换码。
     用一个字节的7位可以表示。
ISO8859-1:拉丁码表,欧洲码表。
     用一个字节的8位表示。
GB2312:中国的中文编码表,最多两个字节编码所有字符。
GBK:中国的中文编码表升级,融合了更多的中文文字符号,最多两个字节编码。
Unicode:国际标准码,融合了目前人类使用的所有字符,为每个字符分配唯一的字符码,所有的文字都用两个字节来表示。
UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。

四、标准输入、输出流 (了解)

  • System.in 和 System.out 分别代表了系统标准的输入和输出设备。
  • 默认输入设备是:键盘;
      输出设备是:显示器。
  • System.in 的类型是InputStream。
  • System.out 的类型是PrintStream,其是OutputStream的子类FilterOutputStream的子类。
  • 重定向:通过System类的setIn,setOut方法对默认设备进行改变。
    • public static void setIn(InputStream in)
    • public static void setOut(PrintStream out)
public class OtherStreamTest {
    /*
    从键盘输入字符串,要求将读取到的整行字符串转成大写输出。
    然后继续进行输入操作,直至当输入“e”或者“exit”时,退出程序。

    方法一:使用Scanner实现,调用next()返回一个字符串。
    方法二:使用System.in实现,System.in ---> 转换流 ---> BufferedReader的readLine()。
     */
    public static void main(String[] args) {

        BufferedReader br = null;
        try {
            InputStreamReader isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);

            while (true) {
                System.out.println("请输入字符串:");
                String data = br.readLine();
                if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
                    System.out.println("程序结束");
                    break;
                }

                String upperCase = data.toUpperCase();
                System.out.println(upperCase);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

五、打印流 (了解)

  • 实现将基本数据类型的数据格式转化为字符串输出
  • 打印流:PrintStreamPrintWriter
    • 提供了一系列重载的print()和println()方法,用于多种数据类型的输出。
    • PrintStream和PrintWriter的输出不会抛出IOException异常。
    • PrintStream和PrintWriter有自动flush功能。
    • PrintStream打印的所有字符都使用平台的默认字符编码转换为字节。
      在需要写入字符而不是写入字节的情况下,应该使用PrintWriter类。
    • System.out返回的是PrintStream的实例。
	/*
	文件输出ASCII字符
	*/
    @Test
    public void test1() {
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("test.txt"));
            //创建打印输出流,设置为自动刷新模式(写入换行符或字节'\n'时都会刷新输出缓冲区)
            ps = new PrintStream(fos, true);
            if (ps != null) { //把标准输出流(控制台输出)改成文件
                System.setOut(ps);
            }
            for (int i = 0; i <= 255; i++) { //输出ASCII字符
                System.out.print((char) i);
                if (i % 50 == 0) { //每50个数据一行
                    System.out.println(); //换行
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

六、数据流 (了解)

  • 为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。
  • 数据流有两个类:(用于读取和写出基本数据类型、String类的数据)
    • DataInputStreamDataOutputStream
    • 分别“套接”在InputStream和OutputStream子类的流上。
  • DataInputStream中的方法:
    boolean readBoolean()
    byte readByte()
    char readChar()
    float readFloar()
    double readDouble()
    short readShort()
    long readLong()
    int readInt()
    String readUTF()
    void readFully(byte[ ] b)
  • DataOutputStream中的方法:
    将上述方法的read改为相应的write即可。

注意:读取不同类型的数据的顺序要与当初写入文件时保存的数据的顺序一致!

public class OtherStreamTest {
    /*
    3.数据流
        3.1 DataInputStream 和 DataOutputStream
        3.2 作用:用于读取或写出基本数据类型的变量或字符串

        练习:将内存中的字符串、基本数据类型的变量写出到文件中。
     */
    @Test
    public void test2() {

        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(new FileOutputStream("data.txt"));

            dos.writeUTF("刘德华");
            dos.flush(); //刷新操作,将内存中的数据写入文件。
            dos.write(23);
            dos.flush();
            dos.writeBoolean(true);
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
    将文件中存储的基本数据类型变量和字符串读取到内存中,并保存在变量中。
    
    注意:读取不同类型的数据的顺序要与当初写入文件时保存的数据的顺序一致!
     */
    @Test
    public void test3() {

        DataInputStream dis = null;
        try {
            dis = new DataInputStream(new FileInputStream("data.txt"));

            String name = dis.readUTF();
            int age = dis.read();
            boolean isMale = dis.readBoolean();

            System.out.println("name = " + name);
            System.out.println("age = " + age);
            System.out.println("isMale = " + isMale);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值