IO流

一.流分类

    1.按流方向:输入流(读) ,输出流(写)

    2.按读取方式:字节流  , 字符流

        



二.字节流

1.使用字节流实现文件的拷贝

public class Copy1 {


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


        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("E:/a.txt");
            fos = new FileOutputStream("E:/b.txt", true);
            //定义一个字节数组,减少IO次数
            byte[] buff = new byte[1024];
            //表示读取的字节数,如果未读到,返回-1
            int len = 0;
            while ((len = fis.read(buff)) != -1) {
                fos.write(buff, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fis.close();
            fos.close();
        }

    }
}

2.使用缓冲流包装字节流复制文件(缓冲流是一种包装流)

public class Copy1 {


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


        FileInputStream fis = null;
        FileOutputStream fos = null;

            fis = new FileInputStream("E:/a.txt");
            //使用缓冲流进行包装
            BufferedInputStream bis = new BufferedInputStream(fis, 10000);
            fos = new FileOutputStream("E:/b.txt", true);
            BufferedOutputStream bos = new BufferedOutputStream(fos, 10000);
            //定义一个字节数组,减少IO次数
            byte[] buff = new byte[1024];
            //表示读取的字节数,如果未读到,返回-1
            int len = 0;
            while ((len = bis.read(buff)) != -1) {
                bos.write(buff,0,len);
            }
            bis.close();
            fis.close();
            bos.close();
            fos.close();

    }
}

二.字符流

     使用字符流完成文件拷贝

    

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

        BufferedReader br = new BufferedReader(new FileReader("E:/a.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("E:/b.txt"));


        //临时字符数组
        char[] buff = new char[512];
        int len = 0;
        while ((len = br.read(buff))!=-1){
            bw.write(buff,0,len);
        }
        bw.flush();
        br.close();
        bw.close();

    }
}


三.转换流

    1.转换流的作用:(1)将字节流转换为字符流(从而可以使用字符流的readLine等方法)

                              (2)设置编码

    

public class Trans {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("E:/a.txt"));
        //只有转换流可以设置编码
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter
                        (new FileOutputStream("E:/b.txt"),"utf-8"));
        String str = null;

        while ((str = br.readLine())!=null){
            bw.write(str+"\r\n");
        }

        bw.flush();
        bw.close();
        br.close();
    }
}


四.对象流(实现序列化和可序列化)

public class ObjectStream {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        //序列化
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:/obj.object"));
        oos.writeObject(new Person("王强", 18));
        oos.close();
        //反序列化
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("E:/obj.object"));
        Person p = (Person) ois.readObject();
        System.out.println(p.getName()+""+p.getAge());
    }
}

注意:使用transient修饰的变量不会被序列化



03-20
### 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、付费专栏及课程。

余额充值