IO流

稍微记录一下流的通用使用步骤

复制代码
 1 package io;
 2 
 3 import java.io.Serializable;
 4 
 5 /**
 6  * Person需满足以下要求方可序列化
 7  * 1.实现接口Serializable
 8  * 2.提供一个全局常量:serialVersionUID
 9  * 3.内部所有属性也必须是可序列化的(基本数据类型默认可序列化)
10  * 补充:ObjectInputStream和ObjectOutputStream不可序列化static和transient修饰的成员变量
11  */
12 public class Person implements Serializable {
13     private static final long serialVersionUID = 43443434672L;
14 
15     private String name;
16     private int age;
17 
18     public Person(String name, int age) {
19         this.name = name;
20         this.age = age;
21     }
22 
23     public String getName() {
24         return name;
25     }
26 
27     public void setName(String name) {
28         this.name = name;
29     }
30 
31     public int getAge() {
32         return age;
33     }
34 
35     public void setAge(int age) {
36         this.age = age;
37     }
38 
39     @Override
40     public String toString() {
41         return "Person{" +
42                 "name='" + name + '\'' +
43                 ", age=" + age +
44                 '}';
45     }
46 }
复制代码

以下为几种常用流的使用方式

复制代码
package io;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.*;

/**
 * 一:流的分类
 * 1.操作数据单位:字节流、字符流
 * 2.数据的流向:输入流、输出流
 * 3.流的角色:节点流、处理流
 *
 * 二:流的体系结构
 * 抽象基类             文件流(节点流)            缓冲流(处理流)
 * InputStream        FileInputStream          BufferedInputStream
 * OutputStream       FileOutputStream         BufferedOutputStream
 * Reader             FileReader               BufferedReader
 * Writer             FileWriter               BufferedWriter
 *
 * 三:结论
 * 1.对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
 * 2.对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt...)使用字节流处理
 */
public class FileReaderWriterTest {

    public static void main(String[] args) {
        //相较于当前工程
        File file = new File("hello.txt");
        System.out.println(file.getAbsolutePath());

        File file1 = new File("module\\hello.txt");
        System.out.println(file1.getAbsolutePath());
    }

    @Test
    public void test1() {
        FileReader fileReader = null;
        try {
            //1.实例化File类对象,指明要操作的文件
            File file = new File("hello.txt");//相较于当前Module
            //2.提供具体的流
            fileReader = new FileReader(file);
            //3.数据的读入
            int data;
            //read():返回读入的一个字符(转化为了ASCII表中对应的整数),如果达到文件末尾,返回-1。
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流的关闭操作
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void test2() {
        FileReader fileReader = null;
        try {
            File file = new File("hello.txt");
            fileReader = new FileReader(file);
            //read(char[] cbuf):返回每次读入cbuf数组中字符的个数,达到文件末尾返回-1
            char[] cbuf = new char[5];
            int len;
            while ((len = fileReader.read(cbuf)) != -1) {
                for (int i = 0; i < len ; i++) {
                    System.out.print(cbuf[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 输出操作:
     *   File对应的硬盘中的文件如果不存在,则会自动创建文件
     *                     如果存在:如果流使用的构造器是:
     *                          FileWriter(file)\FileWriter(file,false),对原有文件进行覆盖
     *                          FileWriter(file,true),对原有文件进行追加
     */
    @Test
    public void test3() {
        FileWriter fileWriter = null;
        try {
            //1.实例化File类对象,指明要操作的文件
            File file = new File("hello1.txt");
            //2.提供具体的流
            fileWriter = new FileWriter(file,true);
            //3.数据的写出
            fileWriter.write("hello1\n");
            fileWriter.write("world1");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                //4.流的关闭操作
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test4() {
        FileReader fileReader = null;
        FileWriter fileWriter = null;
        try {
            //1.创建File类的对象,指明读入和写出的文件
            File srcFile = new File("hello.txt");
            File destFile = new File("hello2.txt");

            //2.创建输入流和输出流的对象
            fileReader = new FileReader(srcFile);
            fileWriter = new FileWriter(destFile);

            //3.数据的读入和写出操作
            char[] cbuf = new char[5];
            int len;
            while ((len = fileReader.read(cbuf)) != -1) {
                //每次写len个字符
                fileWriter.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭流资源
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 提高流的读取,写入的速度:有个缓冲区
     */
    @Test
    public void test5() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            File srcFile = new File("视频IO测试.avi");
            File destFile = new File("备份.avi");

            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);

            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer,0,len);
            }
            //刷新缓冲区,强迫输出流发送数据,即使缓冲区未满
            //bos.flush();
        } catch (IOException 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();
                }
            }
            //fos.close();
            //fis.close();
        }
    }

    @Test
    public void test6() {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(new File("hello.txt")));
            bw = new BufferedWriter(new FileWriter(new File("hello3.txt")));
            String data;
            while ((data = br.readLine()) != null) {
                bw.write(data);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 转换流(处理流)
     * InputStreamReader:将字节的输入流转化为字符的输入流
     * OutputStreamWriter:将字符的输出流转化为字节的输出流
     */
    @Test
    public void test7() {
        InputStreamReader isr = null;
        try {
            FileInputStream fis = new FileInputStream("hello2.txt");
            //字符集取决于文件保存时使用的字符集
            isr = new InputStreamReader(fis,"UTF-8");
            char[] cbuf = new char[5];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                System.out.println(new String(cbuf,0,len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test8() {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            FileInputStream fis = new FileInputStream("hello2.txt");
            FileOutputStream fos = new FileOutputStream("hello4.txt");
            isr = new InputStreamReader(fis,"UTF-8");
            osw = new OutputStreamWriter(fos,"GBK");
            char[] cbuf = new char[5];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                osw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 序列化:将内存中的Java对象或基本数据类型的数据保存到磁盘或通过网络传输出去
     */
    @Test
    public void test9() {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("obj.dat"));
            oos.writeObject(new String("数据流只能作用于基本数据类型"));
            oos.flush();

            oos.writeObject(new Person("张三", 23));
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 反序列化:将磁盘的数据还原到内存中
     */
    @Test
    public void test10() {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("obj.dat"));
            Object o1 = ois.readObject();
            Object o2 = ois.readObject();
            System.out.println((String) o1);
            System.out.println((Person) o2);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 在https://mvnrepository.com/artifact/commons-io/commons-io下载jar包
     */
    @Test
    public void test11() {
        File srcFile = new File("hello.txt");
        File destFile = new File("hello5.txt");

        try {
            FileUtils.copyFile(srcFile,destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
复制代码

 

posted @   Java厨师长  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示