首页 > 其他分享 >IO流读写文件(字节流(单个字节,字节数组),字节缓冲流(..),字符流(..),字符缓冲流(..))

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

时间:2024-10-18 22:21:41浏览次数:1  
标签:字节 .. int 缓冲 System write new public String

        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();
    }
}

标签:字节,..,int,缓冲,System,write,new,public,String
From: https://www.cnblogs.com/wangxiaojian-lina/p/18475154

相关文章

  • while循环和do循环、缓冲区、一维数组
    缓冲区输入缓冲区从键盘得到数据的时候用户输入的数据首先进入输入缓冲区,然后程序从输入缓冲区里获得数字,先进入输入缓冲区的数据必须先处理(类似排队),如果先进入输入缓冲区的数据无法处理,程序就得不到后进入输入缓冲区的数据。使用以下两条固定语句可以删除输入缓冲区里的无效数......
  • 【MySQL】[HY000][1366] Incorrect string value: ‘\xE4\xB8\xA4\xE6\x95\xB0.
    问题描述在导入中文数据时遇到错误。[2024-10-1610:49:49][HY000][1366]Incorrectstringvalue:'\xE4\xB8\xA4\xE6\x95\xB0...'forcolumn'title'atrow1尝试将某些数据插入到名为’title’的列时,遇到了不正确的字符串值。原因分析MySQL5.7创建数据库的默......
  • CMDB不值得...
    在运维管理中,CMDB是一直是一个争议较大的产品,或者说作为一种管理理念,认同这一理念的人将之奉为圭臬,不惜花几十上百万、甚至数百万来打造CMDB,不认同的人觉得它甚至还不如Excel表格实用。01.被误解的CMDB实际上,CMDB可能并没有想像中的那么好,但也没有那么糟糕。作为一个泊来品,CMDB......
  • ERROR require() of ES Module ...\node_modules\string-width\index.js from ...
    nuxt3安装jq的依赖,其实不止jq,只要是安装个新的依赖就报错:ERRORrequire()ofESModule...\node_modules\string-width\index.jsfrom...\node_modules\wide-align\align.jsnotsupported.解决方案:删掉yarn.lock和node_modules重新安装则没问题,然后在github和gi......
  • 分享字节跳动的免费AI编程助手(豆包MarsCode)
    邀请新用户注册登录&使用即可赚火星币,凭对应火星币可赢取京东卡和现金,最高可达1万元。接下来来手把手教你如何参与活动,推广赢好礼!合伙人推广赢好礼1.成为合伙人STEP1:点击https://www.marscode.cn/events/s/iBEnTPtB/,进入活动页面,点击【点击赚钱】按钮。 STEP2:活动页面......
  • 宽字节注入
    文章目录转义函数宽字节注入单双引号被过滤转义函数magic_quotes_gpc()该函数在php中的作用是判断解析用户提示的数据,如包括有:post、get、cookie过来的数据增加转义字符“\”,以确保这些数据不会引起程序,特别是数据库语句因为特殊字符引起的污染而出现致命的错误......
  • Incorrect string value: ‘\xE8\x8D\x98\xE8\x83\xBD...‘ for column
    mysql>SELECTVERSION();+------------+|VERSION()|+------------+|5.6.51-log|+------------+1rowinset(0.00sec)[2024-10-1513:51:26]已连接>useproductqualification[2024-10-1513:51:26]在3ms内完成productqualification>INSERTINTO`......
  • vue3简单使用threejs立方缓冲几何体(BoxGeometry)
    文章目录前言一、安装three二、使用步骤1.导入three、建立场景、相机和渲染器2.添加立方体3.渲染循环三、其他1.轨道控制器OrbitControls和坐标轴辅助对象AxesHelper2.GUI创建可交互的控件(点击全屏+退出全屏)3.监听窗口的变化执行一些重置操作四、完整代码五、效......
  • 明显感觉到今年的Java后端面试风向变了,难怪现在很多人都找不到工作.....
    互联网公司太多了但一些相关的面试步骤和注意事项是大差不差的,我们就以腾讯公司面试为例:面试流程......
  • 串口HEX字节流交互协议解析库分享
    通信协议解析库说明一、概述用于上位机串口通讯协议解析,协议格式:AAlentypeiddata校验帧头(1byte)长度(1byte)协议类型(1byte)命令ID(1byte)数据(xbyte)校验和(1byte)AAxxxx异或校验和固定帧头:0xAA校验和:从AA到校验和之前的所有字节进行异或校验......