IO流读写文件(字节流(单个字节,字节数组),字节缓冲流(..),字符流(..),字符缓冲流(..))

wangxiaojian-lina / 2024-10-23 / 原文

        IO流【输入输出流】:
        按照流向划分:
            输入流:外部数据 -> java程序
            输出流:java程序 -> 外部数据

        按照数据类型划分【根据使用记事本打开是否能够看懂来决定】:
            字节流【万能流】:
                字节输出流:
                    OutputStream(抽象类)
                        - FileOutputStream(实现子类)

                字节输入流:
                    InputStream(抽象类)
                        - FileInputStream(实现子类)
            字符流【记事本能看懂】:
                字符输入流:
                字符输出流:

        FileInputStream:
            构造方法:
                FileInputStream(File file)
                FileInputStream(String name)
            成员方法:
                public int read()

                public int read(byte[] b)

      FileOutputStream:
        构造方法:
            FileOutputStream(File file)
            FileOutputStream(String name)

FileOutputStream构造方法

点击查看代码
  // FileOutputStream(File file) 将目标文件封装成File对象
        // 若目标文件不存在,则会自动创建
        FileOutputStream fos = new FileOutputStream(new File("src/com/shujia/day16/student.txt"));

        //FileOutputStream(String name)
        FileOutputStream fos = new FileOutputStream("src/com/shujia/day16/student.txt");
    public void write(int b)
    public void write(byte[] b)
    public void write(byte[] b,int off,int len)
点击查看代码
    public static void main(String[] args) throws Exception {
        //1、如何实现文件内容追加写? 使用另一个重载的构造方法传入append参数值,没有的话就是直接被替代
        FileOutputStream fos = new FileOutputStream("src/com/shujia/day16/teacher.txt",true);//new FileOutputStream后加true实现追加

        //public void write(int b) 写一个ASCII码值
        fos.write(65);

        // public void write(byte[] b) 写一个字节数组到文件中
      byte[] bytes =   {97,98,99,100,101,102};
      fos.write(bytes);
//        public void write(byte[] b,int off,int len)//截取字节数组一段
        fos.write("\r\n".getBytes());//换行
      fos.write(bytes,2,3);

使用字节输入流读取汉字

点击查看代码
    public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("src/com/shujia/day16/a1.txt");
        fos.write("你今天真的是太棒了".getBytes());
        fos.write("\r\n".getBytes());
        fos.write("喜喜".getBytes());
        FileInputStream fis = new FileInputStream("src/com/shujia/day16/a1.txt");
        //一次读一个字节
        int i= 0;
        while((i = fis.read())!=-1){
            System.out.print((char) i);
        }


//   一次读一个字符数组
        byte[] bytes = new byte[1024];
        int length = 0;
        while((length=fis.read(bytes))!=-1){
          String s = new String(bytes, 0, length);
              System.out.println(s);
}


        //释放资源(顺序与创建顺序相反)
        fis.close();
        fos.close();


    }
    复制文件:
        数据源:D:\girl.jfif
            输入流:
                字节输入流:InputStream
                            - FileInputStream
        目的地:C:\我老婆.jfif
            输出流:
                字节输出流:OutputStream
                            - FileOutputStream
点击查看代码
public class CopyFileTest1 {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:\\girl.jpg");
        FileOutputStream fos = new FileOutputStream("C:\\aaa\\我的大B老婆.jpg",true);

        //一次读一个字节
//        int i = 0;
//        while((i = fis.read()) != -1){
//            fos.write(i);
//        }
        //一次读一个字节数组
        byte[] bytes = new byte[1024];
        int length = 0;
        while((length=fis.read(bytes))!=-1){
            fos.write(bytes,0,length);
        }


//释放资源
        fos.close();
        fis.close();

    }
}

    OutputStream:
        FileOutputStream【普通的字节输出流】:
        BufferedOutputStream【字节缓冲输出流】:
点击查看代码
    public static void main(String[] args) throws Exception {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src/com/shujia/day16/a2.txt", true));
        bos.write("我真的帅".getBytes());
        bos.write("\r\n".getBytes());
        bos.write("你没有我帅".getBytes());

        bos.flush();//缓冲写入需要刷新一次

   bos.close();
    }
    InputStream:
        FileInputStream【普通的字节输入流】:
        BufferedInputStream【字节缓冲输入流】:
点击查看代码
    public static void main(String[] args) throws Exception{
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("src/com/shujia/day16/a2.txt"));
        // 一次读一个字节
//        int i = 0;
//        while ((i=bis.read())!=-1){
//            System.out.print((char) i);
//        }

        // 一次都一个字节数组
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = bis.read(bytes)) != -1) {
            String s = new String(bytes, 0, length);
            System.out.print(s);
        }


        //释放资源
        bis.close();


    }

复制视频到文件夹的速度大比拼
字节缓冲输入流最快

点击查看代码
package com.shujia.day16;

import java.io.*;

//比较4种复制读写的速度
//数据源:E:\bigdata32\32期day16 字节流 1.mp4
public class CopyFileTest2 {
    public static void main(String[] args) {
fun4();
    }
    public static void fun1(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
  try{
      fis= new FileInputStream("D:\\Video\\shujia.mp4");
      fos= new FileOutputStream("C:\\Video\\shujia.mp4");
      // 一次读一个字节
      int i =0;
      int count = 1;
      long start = System.currentTimeMillis();//设置开始时间戳
      while ((i = fis.read())!=-1) {
          fos.write(i);
          System.out.println(count++);
      }
      long end = System.currentTimeMillis();//设置结束时间戳
      System.out.println("共消耗" + (end-start)+"毫秒");

  }catch (Exception e){
      e.printStackTrace();

  }finally {
      if(fis != null){
          try {
              fis.close();
          }catch (Exception e){
              e.printStackTrace();
          }

      }
      if(fos != null){
          try {
              fos.close();
          }catch (Exception e){
              e.printStackTrace();
          }

      }

  }


    }
    public static void fun2()
    {
        FileInputStream fis =null;
        FileOutputStream fos=null;

        try {   fis = new FileInputStream("D:\\Video\\shujia.mp4");
                fos = new FileOutputStream("C:\\Video\\shujia.mp4");
            //一次读一个字节数组
            byte[] bytes = new byte[1024];
            int length = 0;
            int count = 1;
            long start = System.currentTimeMillis();
            while((length = fis.read(bytes)) != -1){
                fos.write(bytes,0,length);
                System.out.println(count++);
            }
            long end = System.currentTimeMillis();
            System.out.println("共消耗" + (end-start)+"毫秒");

        }catch (Exception e){
            e.printStackTrace();


        }finally {
            if(fis != null){
                try {
                    fis.close();
                }catch (Exception e){
                    e.printStackTrace();

                }
            }
            if(fos != null){
                try {
                    fis.close();
                }catch (Exception e){
                    e.printStackTrace();

                }
            }

        }

    }
    //字节缓冲流一次读一个字节
    public static void fun3(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //创建普通字节输入流对象
            bis = new BufferedInputStream(new FileInputStream("D:\\Video\\shujia.mp4"));
            //创建普通字节输出流对象那个
            bos = new BufferedOutputStream(new FileOutputStream("C:\\Video\\shujia.mp4"));

            int i = 0;

            int i2 = 1;
            long start = System.currentTimeMillis();
            while ((i=bis.read())!=-1){
                System.out.println(i2++);
                bos.write(i);
                bos.flush();
            }

            long end = System.currentTimeMillis();
            System.out.println("共消耗 "+(end-start)+" 毫秒");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void fun4(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //创建普通字节输入流对象
            bis = new BufferedInputStream(new FileInputStream("D:\\Video\\shujia.mp4"));
            //创建普通字节输出流对象那个
            bos = new BufferedOutputStream(new FileOutputStream("C:\\Video\\shujia.mp4"));

            byte[] bytes = new byte[1024];
            int length = 0;

            long start = System.currentTimeMillis();
            while ((length= bis.read(bytes))!=-1){
                bos.write(bytes,0,length);
                bos.flush();
            }

            long end = System.currentTimeMillis();
            System.out.println("共消耗 "+(end-start)+" 毫秒");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

    字符流【转换流】:字节流 + 编码表

    密码学


    编码:加密
    解码:解密

    字符流:
        字符输入流:
            Reader
        字符输出流:
            Writer【抽象类】
                - OutputStreamWriter【具体实现子类】
        字符输出流:
            Writer【抽象类】
                - OutputStreamWriter【具体实现子类】

    OutputStreamWriter:
        构造方法:
            OutputStreamWriter(OutputStream out) 创建一个使用默认字符编码的OutputStreamWriter。
            OutputStreamWriter(OutputStream out, String charsetName) 创建一个使用命名字符集的OutputStreamWriter。
        成员方法:
            public void write(int c)
            public void write(char[] cbuf)
            public void write(char[] cbuf,int off,int len)
            public void write(String str)
            public void write(String str,int off,int len)
点击查看代码
    public static void main(String[] args) throws Exception {
//        String s = "今天的你真厉害";
//        byte[] bytes = s.getBytes();
//        System.out.println(Arrays.toString(bytes));
//        String s1 = new String(bytes);
//        System.out.println(s1);
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src/com/shujia/day16/a3.txt",true),"GBK");
//        //一次写入一个字符
//        osw.write(97);
//        osw.flush();
        //一次写入一个字符数组
        char[] c = {'我','爱','中','国'};
//        osw.write(c);
//        osw.flush();
        //public void write(char[] cbuf,int off,int len) 一次写字符数组的一部分
//        osw.write(c,1,3);
//        osw.flush();
//        public void write(String str) 直接写一个字符串
        osw.write("我是真的父类");
        osw.flush();


        //释放资源
        osw.close();






    }
       InputStreamReader:
            构造方法:
                InputStreamReader(InputStream in) 创建一个使用默认字符集的InputStreamReader。
                InputStreamReader(InputStream in, String charsetName) 创建一个使用命名字符集的InputStreamReader。
            成员方法:
                public int read()
                public int read(char[] cbuf)
点击查看代码
   public static void main(String[] args) throws Exception {
        //        InputStreamReader isr = new InputStreamReader(new FileInputStream("java/src/com/shujia/day16/a3.txt"));
        //InputStreamReader(InputStream in, String charsetName)
        InputStreamReader isr = new InputStreamReader(new FileInputStream("java/src/com/shujia/day16/a3.txt"), "GBK");


        // public int read() 一次都一个字符
//        System.out.print((char) isr.read());
//        System.out.print((char) isr.read());
//        int i = 0;
//        while ((i = isr.read()) != -1) {
//            System.out.print((char) i);
//        }

        //public int read(char[] cbuf) 一次读取一个字符数组
        char[] chars = new char[1024];
        int length = 0;
        while ((length= isr.read(chars))!=-1){
            String s = new String(chars, 0, length);
            System.out.print(s);
        }


        // 释放资源
        isr.close();

    }
    把src/com/shujia/day16/a4.txt内容复制到src/com/shujia/day16/b3.txt中
    数据源:src/com/shujia/day16/a3.txt
        字符输入流:
            Reader:
                - InputStreamReader
    目的地:src/com/shujia/day16/b3.txt
        字符输出流:
            Writer:
                - OutputStreamWriter
点击查看代码
        InputStreamReader isr = new InputStreamReader(new FileInputStream("src/com/shujia/day16/a3.txt"));
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src/com/shujia/day16/b3.txt"));

        int i = 0;
        long start = System.currentTimeMillis();


        while((i = isr.read())!= -1){
            osw.write(i);
            osw.flush();
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);

//        char[] chars = new char[1024];
//        int length = 0;
//        long start1 = System.currentTimeMillis();
//        //释放资源
//        while((length=isr.read(chars))!=-1){
//            osw.write(chars,0,length);
//            osw.flush();
//        }
//        long end1 = System.currentTimeMillis();
//        System.out.println(end1 - start1);
        osw.close();
        isr.close();

    字符流:
        字符输入流:
            Reader【抽象类】
                - InputStreamReader【具体实现子类】
                    - FileReader【继承自InputStreamReader】
                - BufferedReader 【字符缓冲输入流】

        字符输出流:
            Writer【抽象类】
                - OutputStreamWriter【具体实现子类】
                    - FileWriter【继承自OutputStreamWriter】
                - BufferedWriter【字符缓冲输出流】
 BufferedWriter【字符缓冲输出流】:
            构造方法:
                BufferedWriter(Writer out) 创建使用默认大小的输出缓冲区的缓冲字符输出流。
            特殊方法:
                newLine(); // 默认会自动根据当前的系统生成一个换行符
点击查看代码
public class BufferedWriterDemo1 {
    public static void main(String[] args) throws Exception{

        BufferedWriter bw = new BufferedWriter(new FileWriter("src/com/shujia/day16/a4.txt"));
        bw.write("hello");
        bw.newLine();
        bw.write("world");
        bw.flush();

        bw.close();

    }
}


        BufferedReader 【字符缓冲输入流】:
            构造方法:
                BufferedReader(Reader in) 创建使用默认大小的输入缓冲区的缓冲字符输入流。
            特殊功能:
                public String readLine() 一次读取文本文件内容的一行, 不会读取换行符
点击查看代码
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("src/com/shujia/day16/a4.txt"));
        //一次读一个字符
//        int i = 0;
//        while ((i=br.read())!=-1){
//            System.out.print((cha) i);
//        }r

        //一次读一个字符数组
//        char[] chars = new char[1024];
//        int length = 0;
//        while ((length=br.read(chars))!=-1){
//            String s = new String(chars, 0, length);
//            System.out.print(s);
//        }

        //一次读一行数据
        //System.out.println(br.readLine());
//        System.out.println(br.readLine());
//        System.out.println(br.readLine());
//        System.out.println(br.readLine());
        String line = null;
        while((line= br.readLine()) != null){
            System.out.println(line);
        }
        //释放资源
        br.close();

    }

字符缓冲流存储

点击查看代码
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new FileReader("src/com/shujia/day16/a4.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("src/com/shujia/day16/b4.txt"));
        //一次读一个字符数
//        int i  = 0;
//        while((i= br.read())!=-1){
//            bw.write(i);
//            bw.flush();
//        }
//        //一次读一个字符数组
//        char[] chars = new char[1024];
//        int length = 0;
//        while((length=br.read(chars))!=-1){
//            bw.write(chars,0,length);
//            bw.flush();
//        }

        String line = null;
        while ((line = br.readLine())!=null){
            bw.write(line);
            bw.flush();
            bw.newLine();
        }

        bw.close();
        br.close();
    }
    已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl”
    请编写程序读取数据内容,把数据排序后写入ss.txt中。
点击查看代码
public class IOTest1 {
    public static void main(String[] args) throws Exception{
        String s = "hcexfgijkamdnoqrzstuvwybpl";
        char[] ch = s.toCharArray();
        Arrays.sort(ch);
//        String s1 = new String(ch);
//        System.out.println(s1);
        BufferedWriter bw = new BufferedWriter(new FileWriter("src/com/shujia/day16/ss.txt"));
        bw.write(ch);
        bw.flush();

        bw.close();
    }
}