IO流的自我实现和总结

1/4文件流

FileInputStream字节输入流

    @Test
    public void test5() throws IOException {
    
    
        //FileInputStream字节输入流
        //a.txt内容为:qw123
        //测试内容1:read()方法
		        //int read(byte[] b)
		        // int read(byte[] b, int off, int len)
		        // int read()
        //测试内容2:循环读取数据
		        //单个字节读取
		        //字节数组循环读取

        //=======================================================================================================
        FileInputStream fis = new FileInputStream("C:\\123\\a.txt");
        //====================================================测试内容1开始
        // int read(byte[] b)
        //          从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
        /*byte[] bytes = new byte[4];
        int readCount1 = fis.read(bytes);
        System.out.println(new String(bytes, 0, readCount1));*/

        //=====================================
        // int read(byte[] b, int off, int len)
        //          从此输入流中将最多 len 个字节的数据读入一个 byte 数组中
        /*byte[] bytes = new byte[5];
        int readCount = fis.read(bytes, 0, 2);
        System.out.println(new String(bytes, 0, readCount));*/

        //===================================
        // int read()
        //          从此输入流中读取(下)一个数据字节

        /*int readCount1 = fis.read();
        System.out.println(readCount1);   //113    对应字符为q
        int readCount2 = fis.read();
        System.out.println(readCount2);   //119    对应字符为w
        int readCount3 = fis.read();
        System.out.println(readCount3);   //49    对应字符为1
        int readCount4 = fis.read();
        System.out.println(readCount4);   //50    对应字符为2*/

        //====================================================测试内容2开始
        //控制台输出结果:
        //qw12
        //3
        /*byte[] bytes = new byte[4];
        int len;
        while ((len = fis.read(bytes)) != -1) {
            System.out.println(new String(bytes, 0, len));
        }

        fis.close();*/
        
        //控制台输出结果:
        //q
        //w
        //1
        //2
        //3
        int len1;
        while ((len1 = fis.read()) != -1) {
    
    
            System.out.println(((char) len1));
        }
    }

FileOutputStream 字节输出流

@Test
    public void test6()throws IOException{
    
    
        //FileOutputStream 字节输出流
        //构造方法
                //        FileOutputStream(File file)   创建一个向指定 File 对象表示的文件中写入数据的文件输出流
                //        FileOutputStream(String name)     创建一个向具有指定名称的文件中写入数据的输出文件流
                //        FileOutputStream(File file, boolean append)       创建一个向指定 File 对象表示的文件中写入数据的文件输出流
        FileOutputStream fos = new FileOutputStream("C:\\123\\b.txt");
        FileOutputStream fos1 = new FileOutputStream("C:\\123\\b.txt", true);


        //b.txt内容为:123
        //测试内容1:write()方法
                //        void write(byte[] b)
                //        将 b.length 个字节从指定 byte 数组写入此文件输出流中。
                //        void write(byte[] b, int off, int len)
                //        将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
                //        void write(int b)
                //        将指定字节写入此文件输出流
        /*fos.write(97);
        fos.write(98);*/


        // byte[] getBytes()
        //          使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中
        String s = "helloworld";
        byte[] bytes = s.getBytes();
        fos.write(bytes);

        /*String s = "helloworld";
        byte[] bytes = s.getBytes();
        fos.write(bytes,0,2);*/


        //测试内容2:几个常见问题
                    //1、实现数据的换行:"\n"、"\r"
                    //2、实现数据的追加写入:
                            // 构造方法FileOutputStream(String name, boolean append)
                            // 创建一个向具有指定 name 的文件中写入数据的输出文件流
                    //3、给IO流操作加上异常处理
        
        //换行
        fos.write("\r".getBytes());
        fos.write("\n".getBytes());//推荐使用
        /*String s1 = System.lineSeparator();
        fos.write(s1.getBytes());*/
        fos.write(97);

        //数据的追加写入
        fos1.write("qwert".getBytes());
        
        fos.close();
    }

用来读取\写入字符文件的便捷类:FileReader FileWriter

    @Test
    public void test7()throws IOException{
    
    
        //字符输入、输出流      FileReader    FileWriter
        //构造方法
                    //        FileReader(String fileName)       在给定从中读取数据的文件名的情况下创建一个新 FileReader

                    //        FileWriter(String fileName)       根据给定的文件名构造一个 FileWriter 对象。
                    //        FileWriter(String fileName, boolean append)       根据给定的文件名以及指示是否附加写入数据的 boolean 值来构造 FileWriter 对象

        FileReader reader = new FileReader("C:\\123\\b.txt");
        FileWriter writer = new FileWriter("C:\\123\\c.txt");

        //测试内容
                    //        int read(char[] cbuf)       将字符读入数组
                    //        void write(char[] cbuf)     写入字符数组
        

        char[] chars = new char[9];   //控制台输出  helloworl
        int read = reader.read(chars);//int read(char[] cbuf)       将字符读入数组
        System.out.println(new String(chars,0,read));//输出字符数组
        
        //================================================================================
        String s = "nihaoa";
        char[] chars1 = s.toCharArray();
        writer.write(chars1);       //写入字符数组


        reader.close();
        writer.close();

    }

2/4缓冲流

BufferedOutputStream、BufferedInputStream

在这里插入图片描述

    @Test
    public void test8()throws IOException{
    
    
        //BufferedOutputStream该类实现缓冲的输出流。通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,
        // 而不必针对每次字节写入调用底层系统
        //BufferedInputStream 为另一个输入流添加一些功能,即缓冲输入以及支持 mark 和 reset 方法的能力

        //构造方法
                    //        BufferedOutputStream(OutputStream out)      创建一个新的缓冲输出流,以将数据写入指定的底层输出流
                    //        BufferedInputStream(InputStream in)     创建一个 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用
        // read方法
        //d.txt内容:asdfg123
                    //        int read()       参见 InputStream 的 read 方法的常规协定。
                    //        int read(byte[] b)        从此输入流中将 byte.length 个字节的数据读入一个 byte 数组中

        //write方法
                    //        void write(int b)        将指定的字节写入此缓冲的输出流
                    //        void write(byte[] b, int off, int len)      将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此缓冲的输出流
                    //        void flush()        刷新此缓冲的输出流

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\123\\d.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\123\\e.txt"));

        //测试方法read==========================================================
        /*int read  = bis.read();
        System.out.println(read);*/
        byte[] bytes = new byte[4];
        int len;
                        //控制台输出:
                        //asdf
                        //g123
        while ((len = bis.read(bytes)) != -1) {
    
    
            System.out.println(new String(bytes, 0, len));
        }
        /*System.out.println(bis.read(bytes,0,2));
        System.out.println(((char) bytes[0]));*/

        //测试方法write==========================================================
//        byte[] bytes1 = {1};//有点问题
        bos.write(bytes);
//        bos.flush();
        bos.close();
        bis.close();

    }

BufferedReader、BufferedWriter

    @Test
    public void test9()throws IOException{
    
    
        //BufferedWriter
                        //     void newLine() 换行
        //BufferedReader        从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取
                        //     String readLine() 读一行数据

        //构造方法:
                        //BufferedReader(Reader in)     创建一个使用默认大小输入缓冲区的缓冲字符输入流
        BufferedReader br = new BufferedReader(new FileReader("C:\\123\\f.txt"));

        //        String readLine()       读取一个文本行
        String s;
        while ((s = br.readLine()) != null) {
    
    
            System.out.println(s);
        }
//        System.out.println(br.readLine());

        br.close();

    }

3/4转换流

InputStreamReader、OutputStreamWriter

InputStreamReader的构造方法:
    		public InputStreamReader(InputStream in)
    		public InputStreamReader(InputStream in,String charsetName)

OutputStreamWriter的构造方法:
            public OutputStreamWriter(OutputStream out)
            public OutputStreamWriter(OutputStream out,String charsetName)
在这里插入代码片

4/4其他流

DataOutputStream、DataInputStream(数据流)

数据输出流 DataOutputStream
        将java基本数据类型写入流中
        java基本数据类型 8个 byte short long int float double char boolean
数据输入流 DataInputStream
        从流中读取java基本数据类型
在这里插入代码片

PrintStream、PrintWriter(打印流)

    @Test
    public void test3() throws IOException {
    
    
        //通俗的讲:将打印信息输出到指定文件中(而非控制台)。
        //PrintStream(OutputStream out, boolean autoFlush) 打印输出流
        //PrintWriter(Writer out, boolean autoFlush)打印输出流

        //System.setOut(ps);                  // 【核心】:对于PrintStream可以把标准输出流(控制台输出)改成文件

        //ps.print(((char) i));               //对于PrintWriter
        //ps.println();

        FileOutputStream fos = new FileOutputStream(new File("C:\\123\\ascii.txt"));//输出流

        // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
        PrintStream ps = new PrintStream(fos, true);
        System.setOut(ps);                  // 【核心】:把标准输出流(控制台输出)改成文件

        for (int i = 0; i <= 255; i++) {
    
     // 输出ASCII字符
            System.out.print((char) i);                 //print()方法
            if (i % 50 == 0) {
    
     // 每50个数据一行
                System.out.println(); // 换行     //println是PrintStream中的方法(重载有多个)
            }
        }
        ps.close();
    }
    @Test
    public void test4() throws FileNotFoundException {
    
    
        //总结见test3()
        FileOutputStream fos = new FileOutputStream(new File("C:\\123\\ascii.txt"));
        
        // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
        PrintWriter ps = new PrintWriter(fos, true);
//        PrintWriter pw = new PrintWriter(fos, true);
        //System.setOut(ps);// 把标准输出流(控制台输出)改成文件
        //ps.print(2048);

        for (int i = 0; i <= 255; i++) {
    
     // 输出ASCII字符
//            System.out.print((char) i);
            ps.print(((char) i));//我的每一个ASCII字符的输出
            if (i % 50 == 0) {
    
     // 每50个数据一行
                //System.out.println(); // 换行
                ps.println();//我的换行
            }
        }
        ps.close();
    }

ObjectOutputStream、ObjectInputStream(数据流)

    @Test
    public void test1() throws IOException, ClassNotFoundException {
    
    
        //对象流2个:ObjectOutputStream和ObjectInputStream

        /*
================================================================
要点:
        对象的序列化:把对象转换为字节序列的过程
        对象的反序列化:把字节序列恢复为对象的过程

        java.io.ObjectOutputStream
        代表对象输出流,它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化,把得到的字节序列写到一个目标输出流中。
        java.io.ObjectInputStream
        代表对象输入流,它的readObject()方法从一个源输入流中读取字节序列,再把它们反序列化为一个对象,并将其返回

        对于参数指定的obj对象:仅实现Serializable接口的类可以 采用默认的序列化方式(class Person implements Serializable)
================================================================
步骤:
        ​对象序列化包括如下步骤:
        1) 创建一个对象输出流,它可以包装一个其他类型的目标输出流,如文件输出流;
        2) 通过对象输出流的writeObject()方法写对象。
        对象反序列化的步骤如下:
        1) 创建一个对象输入流,它可以包装一个其他类型的源输入流,如文件输入流;
        2) 通过对象输入流的readObject()方法读取对象
================================================================
代码实现:
        ObjectOutputStream          序列化       ObjectOutputStream      writeObject
        */

        //序列化       ObjectOutputStream      writeObject
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\123\\d.txt"));
        Person person = new Person(25, "xiaobei");
        out.writeObject(person);    //writeObject(Object obj) 方法:将指定的对象写入 ObjectOutputStream

        //反序列化      ObjectInputStream       readObject
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\123\\d.txt"));
        Person person1 = ((Person) in.readObject());//readObject()方法:从一个源输入流中读取字节序列,
        // 再把它们反序列化为一个对象,并将其返回
        System.out.println(person1);//Person对象的toString()方法已经重写
    }

猜你喜欢

转载自blog.csdn.net/AC_872767407/article/details/113901353