• Java基础-IO流


    简单的使用IO流是很简单的~

     扩展:

    使用追加方式去复制(存储)文件 的格式:

    FileWriter fw = new FileWrite("d:/java/test/ioDemo.txt",true); &FileOutputStream

    在文件里换行:

    ============使用字节流/字符流完成文件复制============

    import java.io.*;
    
    //IO里的对象来自于java.io.*;
    //IO流的输入输出是相对于内存RAM的
    //分类:单位【字节流、字符流】or方向【输入流、输出流】or功能【节点流、处理流】
    //所有的IO流由四个抽象类扩展而来:
    //InputStream 的子类 FileInputStream BufferedInputStream
    //OutputStream 的子类FileInputStream BufferedOutputStream
    //Reader 的子类FileReader BufferedReader
    //Writer 的子类FileWriter BufferedWriter
    public class IOTest {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            // 以下代码用字节流和字符流2种方法完成文件复制功能
            // 1 准备
            String path1 = "D:\Java\Test\红楼梦-曹雪芹.txt";
            String path2 = "D:\Java\Test\程序创建:红楼梦-曹雪芹.txt";
            String path3 = "D:\Java\Test\红楼梦-曹雪芹 - 副本.txt";
            String path4 = "D:\Java\Test\程序创建:红楼梦-曹雪芹 - 副本.txt";
            byte[] b = new byte[1024 * 256];
            char[] c = new char[1024 * 256];
            // 2 声明
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            FileReader fr = null;
            BufferedReader br = null;
            FileWriter fw = null;
            BufferedWriter bw = null;
            // 3 创建
            try {
                fis = new FileInputStream(path1);
                bis = new BufferedInputStream(fis);
                fos = new FileOutputStream(path2);
                bos = new BufferedOutputStream(fos);
                fr = new FileReader(path3);
                br = new BufferedReader(fr);
                fw = new FileWriter(path4);
                bw = new BufferedWriter(fw);
                // 4读取
                int ib = bis.read(b);
                // 5判断-方法1
                long t1 = System.currentTimeMillis();
                while (ib > 0) {
                    // 6复制
                    bos.write(b, 0, ib);
                    // 7循环
                    ib = bis.read(b);
                }
                // 8刷新
                bw.flush();
                long t2 = System.currentTimeMillis();
                System.out.println("使用字节流复制文件完成,用时:" + (t2 - t1) + "毫秒");
                long t3 = System.currentTimeMillis();
                int ic = br.read(c);
                // 判断-方法2
                while (ic > 0) {
                    // 复制
                    bw.write(c, 0, ic);
                    // 循环
                    ic = br.read(c);
                }
                // 刷新
                bw.flush();
                long t4 = System.currentTimeMillis();
                System.out.println("使用字符流复制文件完成,用时:" + (t4 - t3) + "毫秒");
                // =============以下全是异常处理代码段,可以不看=============
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                // 9 关闭
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (fr != null) {
                    try {
                        fr.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (bw != null) {
                    try {
                        bw.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (fw != null) {
                    try {
                        fw.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
    
        }
    
    }

    ============数据流============

    DataInputStream

    DataOutputStream

    数据流的特点是保持基本数据类型的数据不变,实现它们的传递

    常用方法:

    writeInt(int);  &readInt();

    writeDouble(double);  &readDouble();

    ...

    writeUTF(string);  &readUTF();

    数据流属于处理流,所以使用时必须套接在节点流上

    做一个小Demo,代码如下:

    import java.io.*;
    
    //DataIO的使用方法
    public class DataIO {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            // 准备
            String path1 = "D:/java/test/datao.txt";
            //String path2 = "D:/java/test/datai.txt";
            int i = 127;
            double d = 12345678.234567;
            String str = "成都市有个金龙长城";
            String str2 = "成都市有2个金龙长城";
            String str3 = "成都市有3个金龙长城";
            // 声明
            DataOutputStream dos = null;
            DataInputStream dis = null;
            // 创建
            try {
                dos = new DataOutputStream(new FileOutputStream(path1));
                dis = new DataInputStream(new FileInputStream(path1));
                // 复制,按队列顺序存储
                dos.writeInt(i);
                dos.writeDouble(d);
                dos.writeUTF(str);
                dos.writeUTF(str3);
                dos.writeUTF(str2);
                // 刷新
                dos.flush();
                System.out.println("存储成功!");
                // 读取
                System.out.println(dis.readInt());
                System.out.println(dis.readDouble());
                System.out.println(dis.readUTF());
                System.out.println(dis.readUTF());
                System.out.println(dis.readUTF());
                dos.close();
                dis.close();
    
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }//未合理处理异常
        }
    }

    ============对象流============

    ObjectInputStream

    ObjectOutputStream

    为了便于将对象输入输出且保持对象性质,砖家提供了对象流

    常用方法:

    Object readObject();//记得向下转型哦

    void writeObject();

    对象流也是处理流~

    要放进对象流里的自定义的对象的类,必须实现java.io.Serializable接口

    代码示例如下:

    import java.io.*;
    
    //Father是Student的子类,Student要实现Serializable,
    //逻辑上Father必须先实现Serializable,Student才能实现Serializable
    class Father implements Serializable {
        private String name;
    
        public Father() {
            // TODO Auto-generated constructor stub
        }
    
        public Father(String name) {
            super();
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    
    // 要对Student类进行对象流处理,则Student要实现Serializable接口
    class Student implements Serializable {
        // String类也实现了Serializable接口
        private String name;
        private Father father;
    
        public Student() {
            // TODO Auto-generated constructor stub
        }
    
        public Student(String name, Father father) {
            super();
            this.name = name;
            this.father = father;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Father getFather() {
            return father;
        }
    
        public void setFather(Father father) {
            this.father = father;
        }
    
    }
    
    public class ObjectIO {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            // 准备
            Student student01 = new Student("张三", new Father("张三的爸爸"));
            Student student02 = new Student("张三2", new Father("张三2的爸爸"));
            Student student03 = new Student("张三3", new Father("张三3的爸爸"));
            Father father = new Father("1号爸爸");
            Father father2 = new Father("2号爸爸");
            Father father3 = new Father("3号爸爸");
            String path = "d:/java/test/ObjectIO.txt";
            // 声明
            ObjectInputStream ois = null;
            ObjectOutputStream oos = null;
            // 创建
            try {
                oos = new ObjectOutputStream(new FileOutputStream(path));
                // 存储
                oos.writeObject(student01);
                oos.writeObject(student02);
                oos.writeObject(student03);
                oos.writeObject(father);
                oos.writeObject(father2);
                oos.writeObject(father3);
                System.out.println("对象存储完成!");
                // 读取对象值
                ois = new ObjectInputStream(new FileInputStream(path));
                student01 = (Student) ois.readObject();
                student02 = (Student) ois.readObject();
                student03 = (Student) ois.readObject();
                father = (Father) ois.readObject();
                father2 = (Father) ois.readObject();
                father3 = (Father) ois.readObject();
                System.out.println("第一个存放的人的名字:" + student01.getName() + "他/她爸爸的名字是:" + student01.getFather().getName());
                System.out.println("第二个存放的人的名字:" + student02.getName() + "他/她爸爸的名字是:" + student02.getFather().getName());
                System.out.println("第三个存放的人的名字:" + student03.getName() + "他/她爸爸的名字是:" + student03.getFather().getName());
                System.out.println(father.getName());
                System.out.println(father3.getName());// 顺序和下面相反
                System.out.println(father2.getName());
                System.out.println("对象输出完成!");
            } catch (IOException | ClassNotFoundException e) {
                // TODO Auto-generated catch block
                System.out.println("发生了异常!");
            } finally {
                // 简单处理异常、资源关闭
                try {
                    ois.close();
                    oos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    
    }

    ============转换流============

    InputStreamReader; byte→char

    OutpurStreamWriter; char→byte

    为了处理给定的数据流和需要的数据流在单位上发生矛盾的时候,进行转换

    另,转换时可以指定编码方案

    import java.io.*;
    
    public class InputStreamReaderTest {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            // 准备
            String path = "d:/java/test/isrt1.txt";
            // 声明
            InputStreamReader isr = null;
            OutputStreamWriter osw = null;
            try {
                // 创建
                osw = new OutputStreamWriter(new FileOutputStream(path), "utf-8");
                // 存储
                osw.write("欢迎来到北京市");
                osw.close();
                System.out.println("存储完成");
                // 读取
                isr = new InputStreamReader(new FileInputStream(path), "utf-8");
                System.out.println(isr.getEncoding());
                int x = isr.read();
                while (x > 0) {
                    System.out.print((char) x);
                    x = isr.read();
                }
                System.out.println("读取完成");
                isr.close();
            } catch (UnsupportedEncodingException | FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }

    ============打印流============

    PrintStream

    PrintWriter

    打印流属于输出流,打印流属于节点流

    常用方法:

    print()

    println()

    import java.io.FileNotFoundException;
    import java.io.PrintStream;
    
    public class PrintIO {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            // 准备
            String path = "d:/java/test/printio.txt";
            // 声明
            PrintStream ps = null;
            // 创建
            try {
                // =============第一种方法
                ps = new PrintStream(path);
                // 存储
                ps.print("欢迎来上海");
                System.out.println("信息存储完成1");
                // =============第二种方法
                PrintStream old = System.out;
                System.setOut(ps);
                // 这里的输出将保持到文件里
                for (int i = 0; i < 10; i++) {
                    System.out.print(i);
    
                }
                System.setOut(old);
                System.out.println("信息存储完成2");
                // 这里的输出将打印在控制台
    
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }
    
    /**
     * 
     * IO总复习: 1. 四个抽象类[两对] 1) InputStream和OutputStream 抽象的字节输入输出流类。 2) Reader和Writer
     * 抽象的字符输入输出流类
     * 
     * 2. 文件的字节/字符输入输出流类; 1) FileInputStream 和 FileOutputStream 2) FileReader 和
     * FileWriter
     * read() read(byte[] bs)
     * write(int) write(byte[], loc, len);
     * 
     * 3. 缓冲流类: 1) BufferedInputStream 和 BufferedOutputStream 缓冲的字节输入输出流类 
     * 2)BufferedReader 和 BufferedWriter 缓冲的字符输入输出流类 
     * br.readLine(); bw.write(String);bw.newLine();
     * 
     * 4. 数据流类: DataInputStream 数据的字节输入流类 DataOutputStream 数据的字节输出流类 注意:
     * 它们用来实现基本类型的数据及字符串的输入输出. 特色: 保持数据类型不变.
     *  注意: 输入数据的顺序与输出数据顺序要一致. 注意: 它们的方法往往成对出现.
     * 例如: writeByte(byte) byte readByte();
     * 
     * 5. 对象流类: ObjectInputStream 对象的字节输入流类. ObjectOutputStream 对象的字节输出流类.
     * 
     * 注意: 对象对应的类必须实现 java.io.Serializable接口.
     * 
     * 思考: 读取多个对象时会发现什么现象. 注意: writeObject( obj ) Object readObject();
     * 
     * 9. 转换流: InputStreamReader 字节转换成字符的一个转换流.最后,以字符方式来读取数据.
     * 
     * OutputStreamWriter 字符转换字节的一个转换流.最后,以字节方式输出数据.
     * 
     * 注意: 在创建转换流时,可以指定字符的编码方案(字符集).
     * 
     * 10. 打印流: PrintStream 字节打印流. PrintWriter 字符打印流.
     * 
     * 注意: 追加存盘. 注意: 字符流通常用来处理文本文件. 注意: 字节流通常可以处理任意类型的文件.
     * 
     * 11. File 类: 计算机资源的管理类.
     * 
     */
  • 相关阅读:
    OCP-1Z0-053-200题-77题-654
    OCP-1Z0-053-200题-45题-623
    OCP-1Z0-053-200题-46题-624
    OCP-1Z0-053-200题-48题-626
    OCP-1Z0-053-200题-49题-627
    OCP-1Z0-053-V13.02-619题
    OCP-1Z0-053-200题-43题-678
    OCP-1Z0-053-200题-44题-622
    OCP-1Z0-053-V13.02-512题
    OCP-1Z0-053-200题-38题-617
  • 原文地址:https://www.cnblogs.com/qixiawentang/p/5475493.html
Copyright © 2020-2023  润新知