一篇详细讲解java中I/O流的文章

I/O流

I/O流


I/O流

  • 什么是IO
    • input/Output:即输入/输出; JavaIO流,是一种计算机用语。主要是用于处理数据的传输。
  1. 文件

    • 保存数据的地方

    • 常用的文件 操作

      ==new File(String pathname):==根据路径构建一个File对象

      ==new File(File parent,String child):==根据父目录文件+子路径构建

      ==new File(String parent,String child):==根据父目录+子路径构建

      ==createNewFile:==创建新文件

    • 获取文件的相关信息

      ==getName:==获取文件名

      ==getAbsolutePath:==获取绝对路径

      ==getParent:==获取父级目录

      ==length:==获取文件的大小;按字节计算,一个文字3字节,一个字母1字节

      ==exits:==判断文件是否存在

      ==isFile:==判断是否是一个文件

      ==isDiretory:==判断是否是一个目录

    • 目录的操作和文件的删除

      ==mkdir:==创建一级目录

      ==mkdirs:==创建多级目录

      ==delete:==删除空目录或者文件

    代码测试:文件操作

    package com.io.file;
    
    import org.junit.jupiter.api.Test;
    
    import java.io.File;
    
    public class FileOptions {
        @Test
        public void fileOptions(){
            File parentFile = new File("/Users/nile/Studying/javaStudy/basicGrammar/src/com/io/file/");
            String fileName = "news02.txt";
            File file = new File(parentFile, fileName);
            String name = file.getName();
            System.out.println("文件名====>"+name);
            File absoluteFile = file.getAbsoluteFile();
            System.out.println("文件绝对路径====>"+absoluteFile);
            boolean file1 = file.isFile();
            System.out.println("是否是文件====>"+file1);
            boolean exists = file.exists();
            System.out.println("是否存在====>"+exists);
            boolean directory = file.isDirectory();
            System.out.println("是否是目录====>"+directory);
            long length = file.length();
            System.out.println("文件大小====>"+length);//按字节计算的
            String parent = file.getParent();
            System.out.println("父级文件夹=====>"+parent);
    
        }
    }
    
    

    文件的创建:

    package com.io.file;
    
    import org.junit.jupiter.api.Test;
    
    import java.io.File;
    import java.io.IOException;
    
    
    public class FileCreate {
        @Test
        /**
         * new File(String pathname)根据路径构建一个File对象
         */
        public void createFile01(){
            File file = new File("/Users/nile/Studying/javaStudy/basic grammar/src/com/io/file/news.txt");
            try {
                file.createNewFile();
                System.out.println("创建成功~");
            } catch (IOException e) {
                System.out.println("创建失败~");
                throw new RuntimeException(e);
            }
        }
    
        /**
         *
         * new File(File parent,String child)根据父目录文件+子路径构建
         */
        @Test
        public void createFile02(){
            File parentFile = new File("/Users/nile/Studying/javaStudy/basic grammar/src/com/io/file/");
            String fileName = "news02.txt";
            File file = new File(parentFile, fileName);// 只是在程序中存在,要写入磁盘还得用createNewFile
            try {
                file.createNewFile();
                System.out.println("创建02成功~");
            } catch (IOException e) {
                System.out.println("创建02失败~");
                throw new RuntimeException(e);
            }
    
        }
        @Test
        /**
         *
         * new File(String parent,String child)根据父目录+子路径构建
         */
        public void createFile03(){
            String parentPath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/file/";
            String fileName = "news01.txt";
            File file = new File(parentPath, fileName);
            try {
                file.createNewFile();
                System.out.println("创建03成功~");
            } catch (IOException e) {
                System.out.println("创建03失败~");
                throw new RuntimeException(e);
            }
        }
    
    }
    
    
  2. I/O流原理及分类

    • 原理:

      1. I/O时input和output的简称,用于处理数据的传输
      2. 输入(input)流:读取数据到程序
      3. 输出(output)流:将程序中的数据输出到磁盘
    • 分类

      按操作数据单位不同

      • 字节流(8bit)《二进制文件》:字节输入流、字节输出流
      • 字符流(按字符,对应几个字符)《文本文件》:字符输入流、字符输出流

      按数据流向不同

      • 输入流:数据从数据源(文件)到程序(内存)的路径

        InputStream:

        package com.io.standard;
        
        import java.util.Scanner;
        
        public class OutputAndInput {
            public static void main(String[] args) {
                //标准输入流 键盘
                //编译类型是 InputStream
                //运行类型是 BufferedInputStream
                System.out.println(System.in.getClass());
                Scanner scanner = new Scanner(System.in);
                System.out.println("请输入....");
                String next = scanner.next();
                System.out.println("next=" + next);
        
        
                //标准输出流 显示器
                //编译类型是 PrintStream
                //运行类型是 PrintStream
                System.out.println(System.out.getClass());
            }
        }
        
        
        • FileInputStream:文件字节输入流

          package com.io.file;
          
          import org.junit.jupiter.api.Test;
          
          import java.io.FileInputStream;
          import java.io.FileNotFoundException;
          import java.io.IOException;
          
          public class FIleInputStream_ {
              public static void main(String[] args) {
          
              }
              @Test
              /**
               * 单个字节的读取,效率较低
               */
              public void readFile01(){
                  String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/file/news.txt";
                  FileInputStream fileInputStream = null;
                  int readData = 0;
                  try {
                      //创建fileInputStream对象,用于读取文件
                      fileInputStream = new FileInputStream(filePath);
                      //从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
                      //如果返回-1,表示读取完毕
                      try {
                          while ((readData = fileInputStream.read()) != -1){
                              System.out.print((char) readData);// 转为char显示
                          }
                      } catch (IOException e) {
                          throw new RuntimeException(e);
                      }
                  } catch (FileNotFoundException e) {
                      throw new RuntimeException(e);
                  }finally {
                      try {
                          //关闭文件流,释放资源
                          fileInputStream.close();
                      } catch (IOException e) {
                          throw new RuntimeException(e);
                      }
                  }
              }
              @Test
              /**
               * 多个字节的读取,效率较低
               */
              public void readFile02() throws FileNotFoundException {
                  String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/file/news.txt";
                  FileInputStream fileInputStream = null;
                  int readLength = 0;
                  byte[] buffer = new byte[8];// 字节数组
                  try {
                      //创建FileInputStream对象,用于读取文件
                       fileInputStream = new FileInputStream(filePath);
                      try {
                          //从该输入流读取b.length最多的字节的数据到字节数组,
                          //如果返回-1,表示读取完毕,
                          //如果读取正常,返回实际读取的字节数
                          while ((readLength = fileInputStream.read(buffer)) != -1){
                              System.out.print(new String(buffer,0,readLength));//显示
                          }
                      } catch (IOException e) {
                          throw new RuntimeException(e);
                      }
                  } catch (FileNotFoundException e) {
                      throw new RuntimeException(e);
                  }finally {
                      try {
                          //关闭文件流,释放资源
                          fileInputStream.close();
                      } catch (IOException e) {
                          throw new RuntimeException(e);
                      }
                  }
              }
          }
          
          
        • BufferedInputStream:缓冲字节输入流

          package com.io.bufferedReader;
          
          import org.junit.jupiter.api.Test;
          
          import java.io.*;
          
          /**
           *
           *BufferedInputStream和BufferedOutputStream使用他们可以完成二进制文件的拷贝
           * 思考:字节流可以操作二进制文件,可以操作文本文件吗?当然可以
           */
          public class BufferedStream {
              public static void main(String[] args) {
          
              }
              @Test
              public void bufferedInputStream() {
                  String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/bufferedReader/1.jpg";
                  String desPath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/bufferedReader/2.jpg";
                  BufferedInputStream bufferedInputStream = null;
                  BufferedOutputStream bufferedOutputStream = null;
                  try {
                      bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
                      bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(desPath));
                      byte[] bytes = new byte[1024];
                      int readLen = 0;
                      while ((readLen = bufferedInputStream.read(bytes)) != -1){
                          bufferedOutputStream.write(bytes,0,readLen);
                      }
                      System.out.println("文件复制成功....");
                  } catch (IOException e) {
                      System.out.println("文件复制失败....");
                      throw new RuntimeException(e);
                  } finally {
                      if(bufferedInputStream != null){
                          try {
                              bufferedInputStream.close();
                          } catch (IOException e) {
                              throw new RuntimeException(e);
                          }
                      }
                      if(bufferedOutputStream != null){
                          try {
                              bufferedOutputStream.close();
                          } catch (IOException e) {
                              throw new RuntimeException(e);
                          }
                      }
                  }
          
          
              }
          }
          
          
        • ObjectInputStream:对象字节输入流

          Dog类

          package com.io.objectStream;
          
          import java.io.Serializable;
          
          public class Dog implements Serializable {
              private String name;
              private int age;
          
              public Dog(String name, int age) {
                  this.name = name;
                  this.age = age;
              }
          
              public String getName() {
                  return name;
              }
          
              public void setName(String name) {
                  this.name = name;
              }
          
              public int getAge() {
                  return age;
              }
          
              public void setAge(int age) {
                  this.age = age;
              }
          
              @Override
              public String toString() {
                  return "Dog [" + this.getName() + "," + this.getAge() + "]";
              }
          }
          
          
          package com.io.objectStream;
          
          import org.junit.jupiter.api.Test;
          
          import java.io.*;
          
          public class ObjectStream {
              public static void main(String[] args) throws IOException {
          
              }
              //输入  反序列化
              @Test
              public void inputStream() throws IOException{
                  String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/objectStream/data.bat";
                  ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(filePath));
                  System.out.println(objectInputStream.readInt());
                  System.out.println(objectInputStream.readByte());
                  System.out.println(objectInputStream.readBoolean());
                  System.out.println(objectInputStream.readChar());
                  System.out.println(objectInputStream.readUTF());
                  System.out.println(objectInputStream.readDouble());
                  try {
                      System.out.println(objectInputStream.readObject());
                      System.out.println(objectInputStream.readObject());
                      Object o = objectInputStream.readObject();
                      Dog obj = (Dog) o;
                      System.out.println(obj.getName());
                      System.out.println("以反序列化的方式恢复数据成功...");
                  } catch (ClassNotFoundException e) {
                      throw new RuntimeException(e);
                  }
              }
          
          }
          
          

        Reader:

        • FileReader:文件字符输入流

          • 相关方法

            new FileReader(File/String):一个文件或者文件的完整路径

            read:每次读取单个字符,返回该字符,读完饭回-1

            reade(char[]):批量读取多个字符到数组,返回读取到的字符数,读完返回-1

            相关AIPI:

            • new Sring(char[]):将char[]转换成String
            • new Sring(char[],off,length):将char[]指定部分转换成String
        package com.io.file;
        
        import org.junit.jupiter.api.Test;
        
        import java.io.FileNotFoundException;
        import java.io.FileReader;
        import java.io.IOException;
        
        public class FileReader_ {
            public static void main(String[] args) {
        
            }
            @Test
            /**
             * 单个字节读取
             */
            public void fileReader01(){
                String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/file/news02.txt";
                FileReader fileReader = null;
                int buf = 0;
                try {
                    //创建FileReader对象
                   fileReader = new FileReader(filePath);
                    try {
                        while ((buf = fileReader.read()) != -1){
                            System.out.print((char) buf );
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        fileReader.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            @Test
            /**
             * 按字符数组读取
             */
            public void fileRead02(){
                String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/file/news02.txt";
                FileReader fileReader = null;
                char[] buf = new char[20];
                int redaLength = 0;
                try {
                    fileReader = new FileReader(filePath);
                    try {
                        while ((redaLength = fileReader.read(buf)) != -1){
                            System.out.print(new String(buf,0,redaLength));
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        fileReader.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        
        
        • BufferedReader:缓冲字符输入流
        package com.io.bufferedReader;
        
        import org.junit.jupiter.api.Test;
        
        import java.io.*;
        
        /**
         * BufferedReader和BufferedWrite不要用来操作二进制文件,可能会造成文件损坏(如声音、视频文件、doc、pdf)
         */
        
        public class BufferedReader_ {
            public static void main(String[] args) throws IOException {
        
        
            }
            @Test
            /****
             * 读
             */
            public void readerFile() throws IOException{
                String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/bufferedReader/test.txt";
                BufferedReader bufferedReader = null;
                String readLine = null;
                try {
                    bufferedReader = new BufferedReader(new FileReader(filePath));
                    while((readLine = bufferedReader.readLine()) != null){
                        System.out.println(readLine);
                    }
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            @Test
            /****
             * 复制文件
             */
            public void copyFile(){
                String readePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/bufferedReader/test.txt";
                String writePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/bufferedReader/write.txt";
                BufferedReader bufferedReader = null;
                BufferedWriter bufferedWriter = null;
                String rederLine;
                try {
                    bufferedReader = new BufferedReader(new FileReader(readePath));
                    bufferedWriter = new BufferedWriter(new FileWriter(writePath));
                    while ((rederLine = bufferedReader.readLine()) != null){
                        bufferedWriter.write(rederLine);
                        bufferedWriter.newLine();
                    }
                    System.out.println("文件写入成功......");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedWriter != null) {
                            bufferedWriter.close();
                        }
                        if(bufferedReader != null){
                            bufferedReader.close();
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        
        
        • InputStreamReader:字符输入流

          //获取标准输入流
          InputStream is = System.in;
          
          //将字节流转换为字符流
          Reader isr = new InputStreamReader(is);
          //将字符节点流包装为缓冲流
          BufferedReader br = new BufferedReader(isr);
          //读取一行
          String line = br.readLine();
          System.out.println("输入的内容--->"+line);
          
          
      • 输出流:数据从程序(内存)到数据源(文件)的路径

        OutInpuStream:

        • FileOutputStream:文件字节输出流
        package com.io.file;
        
        import org.junit.jupiter.api.Test;
        
        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;
        
        public class FileOuputStream_ {
            public static void main(String[] args) {
        
            }
            @Test
            public void writeFile(){
                String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/file/news.txt";
                FileOutputStream fileOutputStream = null;
                /**
                 * new FileOutputStream(filePath)这种方式创建的对像,会覆盖之前的内容
                 * new FileOutputStream(filePath,true);// 第二个参数表示是否在文件末尾追加,这种方式创建的对象,会追加到文件的末尾,不会覆盖文件原来的内容
                 */
                try {
                    fileOutputStream = new FileOutputStream(filePath,true);
                    try {
                        //这样是一个字节一个字节的写入文件
                        //fileOutputStream.write('h');
                        String str = "wo zuo tian wan shang meng jian ni liao!";
                        //fileOutputStream.write(str.getBytes());
                        //getBytes 可以吧字符串转换为字节数组
                        fileOutputStream.write(str.getBytes(),0,3);// 从什么位置开始追加,追加几个值
                        System.out.println("文件写入成功~");
                    } catch (IOException e) {
                        System.out.println("文件写入失败~");
                        throw new RuntimeException(e);
                    }
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }finally {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        
        
        • BufferedOutputStream:缓冲字节输出流
        package com.io.bufferedReader;
        
        import org.junit.jupiter.api.Test;
        
        import java.io.*;
        
        /**
         *
         *BufferedInputStream和BufferedOutputStream使用他们可以完成二进制文件的拷贝
         * 思考:字节流可以操作二进制文件,可以操作文本文件吗?当然可以
         */
        public class BufferedStream {
            public static void main(String[] args) {
        
            }
            @Test
            public void bufferedInputStream() {
                String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/bufferedReader/1.jpg";
                String desPath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/bufferedReader/2.jpg";
                BufferedInputStream bufferedInputStream = null;
                BufferedOutputStream bufferedOutputStream = null;
                try {
                    bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(desPath));
                    byte[] bytes = new byte[1024];
                    int readLen = 0;
                    while ((readLen = bufferedInputStream.read(bytes)) != -1){
                        bufferedOutputStream.write(bytes,0,readLen);
                    }
                    System.out.println("文件复制成功....");
                } catch (IOException e) {
                    System.out.println("文件复制失败....");
                    throw new RuntimeException(e);
                } finally {
                    if(bufferedInputStream != null){
                        try {
                            bufferedInputStream.close();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    if(bufferedOutputStream != null){
                        try {
                            bufferedOutputStream.close();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
        
        
            }
        }
        
        
        • ObjectOutputStream;对象字节输出流

        Dog类

        package com.io.objectStream;
        
        import java.io.Serializable;
        
        public class Dog implements Serializable {
            private String name;
            private int age;
        
            public Dog(String name, int age) {
                this.name = name;
                this.age = age;
            }
        
            public String getName() {
                return name;
            }
        
            public void setName(String name) {
                this.name = name;
            }
        
            public int getAge() {
                return age;
            }
        
            public void setAge(int age) {
                this.age = age;
            }
        
            @Override
            public String toString() {
                return "Dog [" + this.getName() + "," + this.getAge() + "]";
            }
        }
        
        
        package com.io.objectStream;
        
        import org.junit.jupiter.api.Test;
        
        import java.io.*;
        
        public class ObjectStream {
            public static void main(String[] args) throws IOException {
        
            }
            //输出   序列化
            @Test
            public void outPutStream() throws IOException{
                String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/objectStream/data.bat";
                ObjectOutputStream bufferedOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));
                bufferedOutputStream.writeInt(100);// 底层自动装箱int ----->  Integer,Integer实现了序列化Serializable
                bufferedOutputStream.writeByte(19);// 底层自动装箱byte ----->  Byte,Byte实现了序列化Serializable
                bufferedOutputStream.writeBoolean(true);// 底层自动装箱boolean ----->  Boolean,Boolean实现了序列化Serializable
                bufferedOutputStream.writeChar('a');// 底层自动装箱char ----->  Char,Char实现了序列化Serializable
                bufferedOutputStream.writeUTF("hello,world!");// 底层自动装箱string ----->  String,String实现了序列化Serializable
                bufferedOutputStream.writeDouble(9.3);// 底层自动装箱double ----->  Double,Double实现了序列化Serializable
                bufferedOutputStream.writeObject(new Dog("小黄",10));
                bufferedOutputStream.writeObject(new Dog("小花",2));
                bufferedOutputStream.writeObject(new Dog("小白",5));
                bufferedOutputStream.close();
                System.out.println("以序列化的方式保存成功...");
            }
        

        Writer:

        • FileWriter:文件字符输出流;注意:FileWriter使用后,必须关闭(close)或者刷新(flush),否则写入不到指定的文件

          常用方法:

          new Filewriter(File/String):文件写入覆盖模式

          new Filewriter(File/String,true):文件写入追加模式

          write(int):写入单个字符

          write(char []):写入指定的字符数组

          write(char,off,length):写入指定数组的指定部分

          相关API:String类------>toCharArray:将String转换成char[]

        //基于指定的文件创建字符输出流
        FileWriter fw = new FileWriter("readme.txt");
        fw.write("手握日月摘星辰,世间无我这般人");
        
        //允许在流未关闭之前,强制将字符缓冲区中的数据写出到目标输出源
        fw.flush();
        
        Thread.sleep(10000);
        fw.write("java让整个世界变得更小!!!");
        fw.close();
        
        
        • BufferedWriter:缓冲字符输出流
        package com.io.bufferedReader;
        
        import org.junit.jupiter.api.Test;
        
        import java.io.*;
        
        /**
         * BufferedReader和BufferedWrite不要用来操作二进制文件,可能会造成文件损坏(如声音、视频文件、doc、pdf)
         */
        
        public class BufferedReader_ {
            public static void main(String[] args) throws IOException {
        
        
            }
            @Test
            /****
             * 写
             */
            public void writerFile() throws IOException{
                String filePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/bufferedReader/write.txt";
                BufferedWriter bufferedWriter = null;
                String readLine = null;
                try {
                    bufferedWriter = new BufferedWriter(new FileWriter(filePath));
                    bufferedWriter.write("nninij");
                    bufferedWriter.newLine();
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        bufferedWriter.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
            @Test
            /****
             * 复制文件
             */
            public void copyFile(){
                String readePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/bufferedReader/test.txt";
                String writePath = "/Users/nile/Studying/javaStudy/basic grammar/src/com/io/bufferedReader/write.txt";
                BufferedReader bufferedReader = null;
                BufferedWriter bufferedWriter = null;
                String rederLine;
                try {
                    bufferedReader = new BufferedReader(new FileReader(readePath));
                    bufferedWriter = new BufferedWriter(new FileWriter(writePath));
                    while ((rederLine = bufferedReader.readLine()) != null){
                        bufferedWriter.write(rederLine);
                        bufferedWriter.newLine();
                    }
                    System.out.println("文件写入成功......");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedWriter != null) {
                            bufferedWriter.close();
                        }
                        if(bufferedReader != null){
                            bufferedReader.close();
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        
        
        • OutputStreamWriter:字符输出流,用于将字符输出流转换为字节输出流(字符->字节)
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("test.txt")));
        bw.write("hello,java")
        

      按流的角色不同

      • 节点流:可以从一个特定的数据源**读写数据**

        • FileReader
        • FileWriter
      • 处理流或者包装流:也叫**包装流(对节点流进行包装)**,连接已存在的 (节点流或者处理流),为程序提供更为强大的读写功能,也更加灵活:BufferedReader,有属性Reader,即可以封装一个节点流,该节点流可以事任意的,只要是Reader的子类;BufferedWriter

        • 关闭处理流的时候,只需要关闭外层

        • 二进制处理流:使用他们可以操作二进制文件当然也可以操作文本文件

          BufferedInputStream

          BufferedOutputStream

        • 对象处理流

          • 注意事项⚠️

            读写顺序要一致

            要求实现序列化或者反序列化的对象,要实现Serializable

            序列化的类中建议添加SerialVersionID为了提高版本的兼容性

            序列化时默认将里面所有的属性都进行序列化,但是除了static或者transient修饰的成员

            序列化对象时,要求里面属性的类型也要是实现序列化接口

            序列化的类具备可继承性,也就是说某个类实现了序列化,那么他的子类都实现了序列化

          • 序列化和反序列化

            1. 序列化:

              • 保存数据的时候**保存数据的值和数据类型**:需要让对象支持序列化机制,则必须让其类是支持可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一

              • 保存的文件不是文本文件,而是按照他的格式来保存的,一般是.bat文件

            2. 反序列化:恢复数据的时候恢复数据的值和数据类型

            3. 作用:为了把数据类型也保存起来

          • 标准输入输出流

            System.in

            System.out

            package com.kuang.scanner;
            
            import java.util.Scanner;
            
            public class Demo01 {// 输入流
                public static void main(String[] args) {
                    // 创建一个扫描器对象,用于接受键盘数据
                    Scanner scanner = new Scanner(System.in);
                    System.out.println("使用next方式接收:");
                    // 判断用户有没有输入字符串
                    if(scanner.hasNext()){
                        // next()遇到空格就结束,即不输出空格
                        String str = scanner.next();// 程序会等待用户输入完毕
                        System.out.println("输出的内容为:"+str);
                    }
                    // 凡是属于I/O流的类不关闭会一直占用资源,要养成好的习惯用完就关掉
                    scanner.close();
                }
            }
            
            
            package com.kuang.scanner;
            
            import java.util.Scanner;
            
            public class Demo02 {
                public static void main(String[] args) {
                    Scanner scanner = new Scanner(System.in);
                    System.out.println("使用nextLine方式接收:");
                    if(scanner.hasNextLine()){
                        String str = scanner.nextLine();
                        System.out.println(str);
                        System.out.println("输出的内容为:"+str);
                    }
                    scanner.close();
                }
            }
            
            
            package com.kuang.scanner;
            
            import java.util.Scanner;
            
            public class Demo03 {
                public static void main(String[] args) {
                   Scanner scanner = new Scanner(System.in);
                    System.out.println("请输入一个整数:");
                    if(scanner.hasNextInt()){
                        int i = scanner.nextInt();
                        System.out.println("整数数据:"+i);
                    }else{
                        System.out.println("不是整数数据");
                    }
                    if(scanner.hasNextFloat()){
                        float f = scanner.nextFloat();
                        System.out.println("浮点数据:"+f);
                    }else{
                        System.out.println("不是浮点数据");
                    }
                    scanner.close();
                }
            }
            
            
            package com.kuang.scanner;
            
            import java.util.Scanner;
            
            public class Demo04 {
                public static void main(String[] args) {
                    Scanner scanner = new Scanner(System.in);
                    // 我们可以输入多个数字,并求其和与平均数,每一个数字回车确认,通过非数字来结束输入并输出结束结果
                    double sum = 0;
                    int m = 0;
                    System.out.println("请输入数据:");
                    while (scanner.hasNextDouble()){
                        double s = scanner.nextDouble();
                        sum += s;
                        m++;
                        System.out.println("你输入的第"+m+"个数字,当前的的和是:"+(sum));
                    }
                    System.out.println(m+"个数字的和是"+(sum));
                    scanner.close();
                }
            }
            
            
          • 转换流:把字节流转为字符流

            InputStreamReader(InputStream,charset)

            OutputStreamWriter(OutputStream,charset)

          • 打印流:只有输出流没有输入流

            PrintStream:字节流

            PrintWrite:字符流

  3. 文件Properties类

    用来读取.properties的文件

    用于读取配置文件的集合类:配置文件的格式为:键=值

    • 常见的方法

      load:加载配置文件的键值对倒Properties对象

      list:将数据显示到指定的设备(流对象)

      getProperty(key):根据键获取值

      setProperty(key,value):设置键值对倒Properties对象

      store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储unicode码

    • 父类是hashtable,所以底层方法就是hashtable的方法

      package com.io.properties;
      
      import org.junit.jupiter.api.Test;
      
      import java.io.*;
      import java.util.Properties;
      
      public class Properties_ {
         public static void main(String[] args) throws IOException {
             // 使用properties类来读取mysql.properties文件
      
             // 1.创建Properties对象
             Properties properties = new Properties();
             String filePath = Properties_.class.getResource("").getPath();
             System.out.println(Properties_.class.getResource("").getPath());
             // 2.加载指定的配置文件
             properties.load(new FileReader(filePath + "mysql.properties"));
             // 3.把k-v显示在控制台
             properties.list(System.out);
             properties.setProperty("user","笑话");
             properties.list(System.out);
         }
         @Test
         public void createProperties() throws IOException{
             Properties properties = new Properties();
             properties.setProperty("ip","8.3.3.3");
             properties.setProperty("username","肖荣锋");
             // 如果该文件没有这个键,就是创建,如果有这个key 就是修改这个值
             properties.setProperty("pwd","1234");
             String filePath = Properties_.class.getResource("").getPath();
             System.out.println(Properties_.class.getResource("").getPath());
             // 步骤2:根据绝对路径获取项目所在的目录路径
             String projectPath = filePath.substring(0, filePath.indexOf("out"));
             System.out.println(projectPath+"<------项目路径");
             // 写入的文件中,中文是unicode编码
             properties.store(new FileOutputStream(projectPath + "src/com/io/properties/mysql1.properties"),"我是注释");// 第二个参数表示注释,会在生成文件的开头
             System.out.println("文件保存成功~~~");
         }
      
      }
      
      
      
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值