IO流

1.概念:IO流本质就是一套进行数据传输的机制,

  根据数据传输的方向可分为:   输入流---数据往内存中传输      输出流---数据从内存中往外流出

  根据数据传输的方式可分为:字符流     字节流

  IO流四大基本流都是抽象类

 

 输出流输入流
字符流WriterReader
字节流OutputStreamInputStream

2.缓冲流

   BufferedReader---提供了一个缓冲区

(读文件时会先将内容存入缓冲区),在构建的时候需要传入一个reader对象,真正读取数据时依靠的是这个对象

 public static void main(String[] args) throws Exception {

                                      FileReader reader=new FileReader("D:\\a.txt");
                                      BufferedReader br=new BufferedReader(reader);
                                       String str;

                                //readLine方法表示读取一行数据,读到最后一行会返回null
                                    while((str=br.readLine())!=null){
                                   System.out.println(str)
                                         }

                                          br.close();
                                   }

   BufferedWriter---提供了一个更大的缓冲区

(因为好多输出流本身存在缓冲区,所以此流用的少)

 public static void main(String[] args) throws Exception {
       BufferedWriter writer=new BufferedWriter(new FileWriter("D:\\a.txt"));
               //向文件中写数据
                writer.write("abc");
                 //关流
                writer.close();
    }

3.FileOutputStream---文件字节输出流

   //字节输出流向文件中写数据
    public static void main(String[] args) throws IOException {
        FileOutputStream out=new FileOutputStream("D:\\a.txt");
        //需要将字符转化为字节数组
        out.write("abc".getBytes());
        //写入成功,说明字节输出流没有缓冲区,不需要flush
        out.close();
    }

   FileInputStrem---文件字节输入流

   //字节输入流读取数据
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream=new FileInputStream("D:\\a.txt");
        //定义字节数组作为缓冲区
        byte[]b=new byte[1024];
        int a;

       //将数据读到数组中
        while((a=fileInputStream.read(b))!=-1){
            System.out.println(new String(b,0,a));
        }

        fileInputStream.close()
    }

   FileWriter----文件字符输出流

 //字符输出流向文件中写数据
    public static void main(String[] args) throws IOException {
        FileWriter writer=new FileWriter("D:\\a.txt");
  //先将数据写到缓冲区中,缓冲区未满,程序就已经结束,导致数据死在缓冲区
        writer.write("123");
        //将缓冲区中的数据冲到文件中
        writer.flush();
        writer.close();
    }

   FileReader---文件字符输入流

 //文件字节输入流读取数据
   public static void main(String[] args) throws IOException {
        FileReader reader=new FileReader("D:\\a.txt");
        char[]c=new char[1024];
        int a;
        while((a=reader.read(c))!=-1){
            System.out.println(new String(c,0,a));
        }
        reader.close();
    }

### Java IO概述 Java IO(Input/Output)用于处理数据输入和输出操作。它提供了多种类来实现文件、网络和其他设备的数据传输功能。这些类主要位于 `java.io` 包中。 #### 文件读写的两种基本方式 Java 中的 IO 分为两大类:字节和字符。 - **字节**:适用于二进制数据的操作,例如图片、音频等文件。 - **字符**:专门针对文本文件设计,提供更方便的编码转换支持。 以下是常见的几种及其用途: | 类型 | 输入 | 输出 | |--------------|----------------------------------|-------------------------------| | 字节 | `InputStream` | `OutputStream` | | 字符 | `Reader` | `Writer` | --- ### 示例代码展示 #### 1. 使用字节复制图片文件 下面是一个完整的例子,展示了如何通过字节完成图片文件的复制[^2]。 ```java import java.io.*; public class ByteStreamExample { public static void main(String[] args) { try (InputStream is = new FileInputStream("source_image.png"); OutputStream os = new FileOutputStream("destination_image.png")) { byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } catch (IOException e) { System.err.println("Error occurred during file copy: " + e.getMessage()); } } } ``` 此代码片段实现了从源路径到目标路径的文件拷贝过程。其中使用了缓冲区技术以提高性能。 #### 2. 缓冲字节的应用 为了进一步提升效率,可以引入带缓冲机制的子类——`BufferedInputStream` 和 `BufferedOutputStream`[^3]。 ```java import java.io.*; public class BufferedByteStreamExample { public static void main(String[] args) { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) { int data; while ((data = bis.read()) != -1) { bos.write(data); } } catch (IOException e) { System.err.println("I/O error encountered: " + e.getMessage()); } } } ``` 上述程序利用缓冲特性减少了底层磁盘访问次数,从而加快了执行速度。 #### 3. 对象序列化与反序列化 如果需要保存复杂结构的对象至外部存储介质,则需要用到对象 `ObjectInputStream` 和 `ObjectOutputStream`[^1]。 ```java // 序列化对象 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.ser"))) { MySerializableClass obj = new MySerializableClass(); oos.writeObject(obj); } catch (Exception ex) { System.out.println(ex.toString()); } // 反序列化对象 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.ser"))) { MySerializableClass restoredObj = (MySerializableClass) ois.readObject(); System.out.println(restoredObj); } catch (Exception ex) { System.out.println(ex.toString()); } ``` 注意:要使某个类能够被序列化,该类需实现 `java.io.Serializable` 接口。 --- ### 总结 以上介绍了三种典型场景下的 Java IO 应用实例,分别是基于字节的基础文件操作、借助缓存优化后的高效版本以及面向对象持久化的高级技巧。每种情况都体现了不同层次的需求满足能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值