首页 > 编程语言 >木舟0基础学习Java的第十八天(IO流,字节流,字符流,缓冲)

木舟0基础学习Java的第十八天(IO流,字节流,字符流,缓冲)

时间:2024-07-16 09:56:11浏览次数:14  
标签:第十八天 Java 木舟 RuntimeException catch new null throw out

IO流正常使用流程:1.抛异常  2.资源读写  3.关闭资源(从后往前关)

字节流:(拷贝推荐使用)

开发中一般不会抛出异常 用try{}catch(){} 也不推荐字节流读中文

FileInputStream:读

         FileInputStream fs=new FileInputStream("e:/b.txt");
            //11111111为-1的补码 会认为已经读取完毕 如果用byte 会出现数据读取不完整
            int i=0;
            while((i=fs.read())!=-1){
                System.out.println((char)i);
            }
            //必须关闭资源
            fs.close();
    }

FileOutputStream:写

 public static void main(String[] args) throws Exception {
        //如果e盘下没有b.txt FileOutputStream会自己创建一个
        FileOutputStream fo=new FileOutputStream("e:/b.txt");
        //write 一次写出一个字节
        fo.write(99);//c
        fo.write(100);//d
        fo.close();
        //追加 true代表不覆盖文件中的旧数据 追加到文件末尾
        FileOutputStream fo1=new FileOutputStream("e:/b.txt",true);
        fo1.write(97);
        fo1.write(98);
        fo1.close();
        //连续写入
        FileOutputStream fo2=new FileOutputStream("e:/b.txt");
          String s="abcdefghijklmn";
        //String s="我爱学习";//1f`  字节流写中文会乱码
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            fo2.write(c);
        }
        fo2.close();
    }

读写案例

案例:字节拷贝(读一个字节写一个字节 效率低)
   public static void main(String[] args) throws Exception {
        FileInputStream fs=new FileInputStream("e:/1.jpg");//读
        FileOutputStream out=new FileOutputStream("e:/cba/1.jpg");//写
        int i=0;
        //一边读一边写
        while((i=fs.read())!=-1){//每次读一个字节
            out.write(i);//每次写一个字节
        }
        //先关后面的 再关前面的 关两个
        out.close();
        fs.close();
    }
案例:字节数组拷贝(读总字节写总字节 效率高)

开发中推荐 数组长度byte[] b=new byte[1024*8];

声明一个用来记录读取有效长度的变量 int len=0;

public static void main(String[] args) throws Exception {
        FileInputStream in=new FileInputStream("e:/1.jpg");//读
        FileOutputStream out=new FileOutputStream("e:/cba/1.jpg");//写
        //创建字节数组
        byte[] b=new byte[1024*8];//开发中推荐 数组长度byte[] b=new byte[1024*8];
        int len=0;//声明一个用来记录读取有效长度的变量 int len=0;
        while((len=in.read(b))!=-1){
            System.out.println(len);
            out.write(b,0,len);
        }
        out.close();
        in.close();
    }

 逻辑:

  public static void main(String[] args) throws Exception {
        FileInputStream in=new FileInputStream("e:/1.jpg");//读
        FileOutputStream out=new FileOutputStream("e:/cba/1.jpg");//写
        int available = in.available();//获取文件总字节数
        //创建字节数组
        byte[] b=new byte[available];//创建一个数组 长度是图片所有字节长度
        while(in.read(b)!=-1){
            out.write(b);
        }
        out.close();
        in.close();
    }

Buffered缓冲区:

 public static void main(String[] args) throws Exception {
        FileInputStream in=new FileInputStream("e:/cba/w.mp4");
        BufferedInputStream bis=new BufferedInputStream(in);//自带缓冲区 底层就是new byte[8192]
        FileOutputStream out=new FileOutputStream("e:/abc/w.mp4");
        BufferedOutputStream bos=new BufferedOutputStream(out);//先写到缓冲区 写满后一次性写到文件中
        int b=0;
        while((b=bis.read())!=-1){
            bos.write(b);
        }
        //关闭缓冲区 关闭缓冲区后会自动关闭 in和out
        bos.close();
        bis.close();
    }
数组和Buffered:(开发中推荐数组拷贝)

如果是8192字节大小 数组比Buffered快一些 因为读和写都是同一数组

但是Bufferde操作的是两个数组

关闭资源(close,flush)

close:关闭释放资源 如果是带缓冲区的流对象 不但会关闭流 还会在关闭流之前刷新缓冲区 但是关闭之后不能再写出

flush:用来刷新缓冲区 刷新后可以再写出

开发中标准写法:

 public static void main(String[] args) {
        FileInputStream in=null;
        FileOutputStream out=null;
        try {
          in=new FileInputStream("e:/cba/w.mp4");
          out=new FileOutputStream("e:/abc/ww.mp4");
            int len=0;
            byte[] b=new byte[1024*8];
            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(out!=null){//避免下面报空指针异常
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

案例:用键盘录入数据 写到硬盘  (带缓冲区和不带缓冲区)

public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        FileOutputStream out=null;
        try {
            out=new FileOutputStream("e:/cba/aaa.txt",true);
            while(true){
                System.out.println("请输入:");
                String s=sc.next();
                if(!s.equals("quit")){
                    byte[] b=s.getBytes();
                    out.write(b);
                }else{
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        FileOutputStream out=null;
        BufferedOutputStream bos=null;
        try {
            out=new FileOutputStream("e:/cba/bbb.txt");
            bos=new BufferedOutputStream(out);
            while(true){
                System.out.println("请输入:");
                String s=sc.next();
                if(!s.equals("puit")){
                    byte[] b=s.getBytes();
                    bos.write(b);
                    bos.flush();//刷新缓冲区 及时把缓冲区数据刷入硬盘
                }else{
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            if(bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

字符流:(纯文本时推荐使用)

不可以拷贝非纯文本文件

FileReader:读

 public static void main(String[] args) {
        FileReader r=null;
        try {
            r=new FileReader("e:/cba/a.txt");
            int a=0;
            while((a=r.read())!=-1){
                System.out.println((char)a);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            if(r!=null){
                try {
                    r.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

FileWrite:写

 public static void main(String[] args) {
        FileWriter w=null;
        try {
            w=new FileWriter("e:/cba/n.txt");
            String s="你好,我不好!";
            char[] c = s.toCharArray();//将字符转为字节存入char数组
            w.write(c);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            if(w!=null){
                try {
                    w.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

读写案例

案例:字符拷贝(效率低 容易拷贝不完整)
public static void main(String[] args) {
        FileReader fr=null;
        FileWriter fw=null;
        try {
            fr=new FileReader("e:/cba/a.txt");
            fw=new FileWriter("e:/abc/b.txt");
            int a=0;
            while((a=fr.read())!=-1){
                fw.write(a);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            try {
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                fr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
案例:字符数组拷贝(效率高 拷贝完整)
public static void main(String[] args) {
        FileReader fr=null;
        FileWriter fw=null;
        try {
            fr=new FileReader("e:/cba/a.txt");
            fw=new FileWriter("e:/abc/a.txt");
            char[] c=new char[1024*8];
            int len=0;
            while((len=fr.read(c))!=-1){
                fw.write(c,0,len);
                System.out.println(len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            try {
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                fr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

Buffered缓冲区:

BufferedReader

public static void main(String[] args) {
        FileReader fr=null;
        BufferedReader br=null;
        try {
            fr=new FileReader("e:/abc/a.txt");
            br=new BufferedReader(fr);
            String s=null;
            //br.readLine()方法 可以读取一行字符 但不包括换行符号
            while((s=br.readLine())!=null){
                System.out.println(s);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            try {
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

BufferedWriter

 public static void main(String[] args) {
        FileWriter fw=null;
        BufferedWriter bw=null;
        try {
            fw=new FileWriter("e:/abc/ab.txt");
            bw=new BufferedWriter(fw);
            bw.write("你好");
            bw.write("\r\n");
            bw.write("早上好");
            bw.newLine();//写入一个可以跨平台的换行符 相当于bw.write("\r\n"); 推荐使用!!!
            bw.write("不好!");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            try {
                bw.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

BufferedReader和BufferedWriter

 public static void main(String[] args){
        FileReader fr=null;
        BufferedReader br=null;
        FileWriter fw=null;
        BufferedWriter bw=null;
        try {
            fr=new FileReader("e:/abc/a.txt");
            br=new BufferedReader(fr);
            fw=new FileWriter("e:/cba/t.txt");
            bw=new BufferedWriter(fw);
            String s=null;
            while((s=br.readLine())!=null){
                bw.write(s);
                bw.flush();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

将文本反转案例:

 public static void main(String[] args) {
        //将文本反转
        FileReader fr=null;
        BufferedReader br=null;
        FileWriter fw=null;
        BufferedWriter bw=null;
        try {
            fr=new FileReader("e:/abc/a.txt");
            br=new BufferedReader(fr);
            String s=null;
            StringBuffer sb=new StringBuffer();
            while((s=br.readLine())!=null){
                sb.append(s);
                sb.append("\r\n");
            }
            //反转
            sb.reverse();
            //System.out.println(sb);

            //将sb中的数据全部写入
            fw=new FileWriter("e:/abc/ccc.txt");
            bw=new BufferedWriter(fw);
            bw.write(sb.toString());
            bw.flush();

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

标签:第十八天,Java,木舟,RuntimeException,catch,new,null,throw,out
From: https://blog.csdn.net/tzh525/article/details/140412357

相关文章

  • 木舟0基础学习Java的第十七天(File类使用,IO流)
     File类(路径):文件路径文件夹路径路径:1.绝对路径:固定的路径从盘符开始2.相对路径:相对于某个位置指当前项目下创建功能:Filef=newFile("e:/a.txt");try{booleanb1=f.createNewFile();//新建文件System.out.println(b1);......
  • 在JavaScript中,如何实现异步编程?
    在JavaScript中,如何实现异步编程?请列举几种常见的方法(如Promise、async/await)。在JavaScript中,异步编程是处理长时间运行的任务(如网络请求、文件读写、大量计算等)的关键。JavaScript是单线程的,但通过使用异步编程模式,我们可以编写出既不会阻塞主线程执行又能处理耗时任务的......
  • 基于Java中的SSM框架实现娱乐影视公司管理系统项目【项目源码+论文说明】
    基于Java中的SSM框架实现娱乐影视公司管理系统演示摘要电脑的出现是一个时代的进步,不仅仅帮助人们解决了一些数学上的难题,如今电脑的出现,更加方便了人们在工作和生活中对于一些事物的处理。应用的越来越广泛,通过互联网我们可以更方便地进行办公,也能够在网上就能处理很多日......
  • 基于Java中的SSM框架实现在线考试系统项目【项目源码+论文说明】
    摘要本楚水高中在线考试系统是针对目前楚水高中在线考试的实际需求,从实际工作出发,对过去的楚水高中在线考试系统存在的问题进行分析,结合计算机系统的结构、概念、模型、原理、方法,在计算机各种优势的情况下,采用目前最流行的B/S结构和java中流行的MVC三层设计模式和eclipse编辑......
  • JavaScript系列:JS实现复制粘贴文字以及图片
    目录一.基于ClipboardAPI复制文字(推荐)基本概念主要方法使用限制实际应用示例二、基于document.execCommand('copy')缺陷实际应用示例说明三、复制图片功能四、封装一.基于ClipboardAPI复制文字(推荐)基本概念ClipboardAPI是一组用于在浏览器中操作剪贴板的JavaScript......
  • Java JNI 学习笔记
    JavaJNI学习笔记JNI(JavaNativeInterface)是Java提供的一种接口,使得java代码可以与其他语言(如C和C++)编写的代码进行交互。具体来说,JNI允许你在Java中调用本地(Native)代码,或者从本地代码调用Java方法。基本概念jni.h:这是JNI的头文件,使用javac生成,定义了JNI......
  • UDP网络编程java实现
    UdpUdp服务端实现步骤:创建Udp对象,监听端口创建数据包(数据包,数据长度)接收数据包(数据包)读取数据包,并输出将字节数组转化为字符串响应客户端消息(设置数据包)发送数据包//监听端口号DatagramSocketdatagramSocket=newDatagramSocket(6666);//创建数据包byte[]buff......
  • 【Android面试八股文】1. 说一说Java四大引用有哪些? 2. 软引用和弱引用的区别是什么?
    一、Java四大引用有哪些?在Java中,有四种不同类型的引用,它们在垃圾回收和对象生命周期管理方面有着不同的作用和行为。这四种引用分别是:强引用(StrongReference)软引用(SoftReference)弱引用(WeakReference)虚引用(PhantomReference)下面详细解释每种引用的特点和用途:......
  • [Java基础]HashMap
    HashSet基于哈希表实现的无序集合,它使用哈希算法来存储和检索元素。下面是向HashSet中加入元素的过程:计算哈希码(HashCode):当你向HashSet中添加一个元素时,首先会调用该元素的hashCode()方法,得到元素的哈希码。如果元素为null,则它的哈希码为0。映射到桶位置(BucketP......
  • JavaScript全解析——本地存储✔(localStorage~sessionStorage~cookie)
    ●就是浏览器给我们提供的可以让我们在浏览器上保存一些数据●常用的本地存储(localStorage~sessionStorage~cookie)1-localStorage=>特点:->长期存储,除非手动删除否则会一直保存在浏览器中清除缓存或者卸载浏览器也就没有了->可以跨页面通讯,也就是说在一个页面写下......