Notas de estudio de flujo de Java io

PD: La mayoría de las palabras originales provienen de los materiales de referencia y el resumen es muy bueno, así que no lo he cambiado.

1. ¿Qué puede hacer IO stream?

A través de IO podemos leer y escribir archivos del disco duro. (La transmisión de datos de red también implica io).

2. Clasificación de flujos IO


Clasificar según la dirección del flujo: divididos en flujos de entrada y salida.

Ir a memoria: llamado entrada (Input) . O llamado read (Read) .
De memoria: llamada salida (Output) . O llamado escribir (Write) .


Clasifique según las diferentes formas de leer datos : lea datos en bytes y lea 1 byte a la vez, lo que equivale a leer 8 bits binarios a la vez. Esta transmisión es universal y se puede leer cualquier tipo de archivo. Incluyendo: archivos de texto, imágenes, archivos de sonido, archivos de video, etc...

Lea datos en forma de caracteres ,
un carácter a la vez. Este flujo existe para facilitar la lectura de archivos de texto ordinarios. Este flujo no se puede leer: imágenes, sonido, video y otros archivos. Solo se pueden leer archivos de texto sin formato, ni siquiera archivos de texto.

Nota:
Los archivos de texto sin formato no son solo archivos .txt, sino también .java, .ini y .py. En resumen, siempre que los archivos que se pueden abrir con el Bloc de notas sean archivos de texto ordinarios.

3. La clase principal de nivel superior del flujo IO

    - flujo de entrada de bytes: clase principal de nivel superior: InputStream --> subclase común de clase abstracta: FileInputStream
    - flujo de salida de bytes: clase principal de nivel superior: OutputStream --> subclase común de clase abstracta: FileOutputStream
    - flujo de entrada de caracteres: nivel superior clase principal: Lector --> subclase común de clase abstracta: FileReader
    - flujo de salida de caracteres: clase principal de nivel superior: Escritor --> subclase común de clase abstracta: FileWriter

4. Flujos para ser dominados por Java (16)

1. Archivo exclusivo:

  • java.io.FileInputStream(maestro)¶
  • java.io.FileOutputStream(maestro)¶
  • java.io.FileReader
  • java.io.FileWriter

2. Flujo de conversión: (convertir flujo de bytes en flujo de caracteres)

  • java.io.InputStreamReader
  • java.io.OutputStreamWriter

3. Flujo de búfer exclusivo:

  • java.io.BufferedReader
  • java.io.BufferedWriter
  • java.io.BufferedInputStream
  • java.io.BufferedOutputStream

4. Flujo de datos exclusivo:

  • java.io.DataInputStream
  • java.io.DataOutputStream

5. Flujo de salida estándar:

  • java.io.PrintWriter
  • java.io.PrintStream(maestro)¶

6. Flujo específico del objeto:

  • java.io.ObjectInputStream(maestro)¶
  • java.io.ObjectOutputStream(maestro)¶

7.Clase de archivo

  • java.io.Archivo

5. Flujo de entrada

PD: Muchas de las siguientes excepciones try and catch catch no están escritas por mí. Por supuesto, si lo escribe por primera vez, puede escribirlo usted mismo, pero alt + z puede generarse directa y rápidamente.

Además, esos pocos métodos de uso común (creo), de hecho, escribiré los primeros, pero el resto son más fáciles de recordar.

Mi archivo conf.txt está en el mismo directorio que src.

FileInputStream

public class IODemo1 {
    public static void main(String[] args)  {
        File file = new File("conf.txt");
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);

            byte[] bytes = new byte[3]; // 做缓存用的,一次最多4个字节
            int redCount = 0;

            // inputStream去读取,而每次读取到的字节文件存放到bytes中。
            while ((redCount = inputStream.read(bytes)) != -1){ // read读取值是字节数量,读取不到返回-1
                System.out.println("转换后的字符:"+new String(bytes, "UTF-8"));
                System.out.println("读取字节数量:"+redCount);
                System.out.println("----------------");
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 失败与否都要关闭io
            if(inputStream != null){ // 判断文件是否为null
                try{
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

InputStreamReader

Hay tal manera de escribir.

Convierta un flujo de entrada de bytes en un flujo de entrada de caracteres.

public class IODemo {
    public static void main(String[] args)  {
        File file = new File("conf.txt");
        FileInputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        try {
             inputStream = new FileInputStream(file);
             inputStreamReader = new InputStreamReader(inputStream,"UTF-8"); // 转换为为字符输入流

            byte[] bytes = new byte[3]; // 做缓存用的,一次最多4个字节
            char[] chars = new char[1];
            int redCount = 0;

            // inputStream去读取,每次读取到字节存放到bytes中。
            //while ((redCount = inputStream.read(bytes)) != -1){ // read读取值是字节数量,读取不到返回-1
            //    System.out.println("转换后的字符:"+new String(bytes, "GBK"));
            //    System.out.println("读取字节数量:"+redCount);
            //}
            System.out.println("---------------");
            // 对一个文件不能同时开2个输入流
            while ((redCount = inputStreamReader.read(chars)) != -1){
                System.out.println("读取字符数量:"+redCount);
                for (char aChar : chars) { // 遍历缓冲字符数组
                    System.out.println(aChar);
                }
                System.out.println("将字符数组转换成字符串:"+ new String(chars));
                System.out.println("---------------");
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 失败与否都要关闭io
            if(inputStreamReader != null){
                try{ // 流的关闭要区分顺序,先关闭外层也就是包装那一层
                    inputStreamReader.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

Lector de archivos

La forma de lectura de caracteres de archivo.

public class FileReaderDemo {
    public static void main(String[] args) {
        File file = new File("conf.txt");
        FileReader fileReader = null;
        try {
            char[] chars = new char[4];
            int readCount = 0;
            fileReader = new FileReader(file);
            while ((readCount = fileReader.read(chars)) != -1){
                System.out.println(new String(chars));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileReader != null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

BufferedReader

Un flujo de entrada de caracteres con su propio caché. El parámetro constructor es un flujo de entrada de caracteres.

public class BufferReaderDemo {
    public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("conf.txt");
        // 当一个流的构造方法中需要一个流的时候,这个被传进来的流叫做:节点流。
        // 外部负责包装的这个流,叫做:包装流,还有一个名字叫做:处理流。
        // 像当前这个程序来说:FileReader就是一个节点流。BufferedReader就是包装流/处理流。
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null){ // readLine()方法读取一个文本行,但不带换行符。
            System.out.println(str);
        }

        bufferedReader.close(); // 关闭最外层即可
    }
}

ObjetoEntradaStream

deserializar objeto

        // 反序列化
        ObjectInputStream oin = new ObjectInputStream(new FileInputStream("conf1.txt"));
        Object o = oin.readObject();
        System.out.println(o);

6. Flujo de salida

FileOutputStream


public class IoDemo2 {
    public static void main(String[] args) {
        File file = new File("conf.txt");
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file,true); // 开启文件追加模式
            String wls = "万乐姝";
            byte[] bytes = wls.getBytes(StandardCharsets.UTF_8); // 将string转换为字节文件
            outputStream.write(bytes); // 写入
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                try {
                    outputStream.flush(); // 先刷新在关闭,否则可能有bug
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

OutputStreamWriter

public class IoDemo2 {
    public static void main(String[] args) {
        File file = new File("conf.txt");
        FileOutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            outputStream = new FileOutputStream(file,true); // 开启文件追加模式
            outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write("万乐姝");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                try {
                    outputStreamWriter.flush(); // 先关闭外层流
                    outputStreamWriter.close();
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

FileWriter

public class FileWriterDemo {
    public static void main(String[] args) {
        File file = new File("conf.txt");
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file,true); // 开启文件追加模式
            fileWriter.write("卧槽");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

BufferedWriter

public class BufferWriterDemo {
    public static void main(String[] args) throws IOException {
        FileWriter fileWriter = new FileWriter("conf.txt",true);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write("qhxxxx");
        bufferedWriter.close();

    }
}

flujo de impresión

 La declaración de impresión de la consola que solemos usar es el objeto PrintStream

Cambiar la dirección de salida de la transmisión

System.setOut(PrintStream对象)

 PrintStream printStream = new PrintStream(new FileOutputStream("conf.txt"));
        printStream.println("\n121212"); // 输出到conf.txt
        System.setOut(printStream); // 改变流的输出方向

        System.out.println("\n完了数"); // 输出到conf.txt了
        System.out.println("121212");

ObjectOutputStreamObjectOutputStream

No muy útil para principiantes.

Los objetos a ser serializados deben implementar  la interfaz Serializable

       // 序列化
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new             
        FileOutputStream("conf1.txt"));
        objectOutputStream.writeObject(new User("qhx","1232323"));
        objectOutputStream.flush();
        objectOutputStream.close();

7. Configurar la lectura y configuración del archivo de propiedades

  • getProperty (clave de cadena): busca una propiedad en esta lista de propiedades con la clave especificada. Es decir, a través del parámetro clave se obtiene el valor correspondiente a la clave.
  • load ( InputStream inStream ): lee una lista de propiedades (clave y par de elementos) del flujo de entrada. Obtenga todos los pares clave-valor en un archivo específico (por ejemplo, el archivo test.properties anterior) cargándolo. Para getProperty (clave de cadena) para buscar.
  • setProperty (clave de cadena, valor de cadena): llama al método put de Hashtable. Establece el par clave-valor llamando al método put de la clase base.
  • store (OutputStream out, String comments): escribe la lista de propiedades (clave y pares de elementos) de esta tabla de propiedades en el flujo de salida en un formato adecuado para cargar en la tabla de propiedades mediante el método de carga. A diferencia del método de carga, este método escribe pares clave-valor en el archivo especificado.
  • clear(): Borra todos los pares clave-valor cargados. Este método se proporciona en la clase base.
     

Lectura del archivo de configuración

  private static String getKey(String key) {
        Properties properties = new Properties();
        File file = new File(FILE_NAME);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file); // 配置文件
            properties.load(inputStream); // 将配置文件对应的key,value映射到properties的map中。
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream != null){  // 还是这样关比较好,万一报错就tm关不了
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(properties.getProperty(key));
    }

Configuración de perfil

    /**
     * 配置文件设置
     *
     * @param key
     * @param value
     * @return
     */
    public static boolean setPropertiesKey(String key,String value) {
        // 判断key是否有重复
        String key1 = getKey(key);
        if(key1 == null){
            return setKey(key,value); 
        }
        return false;
    }

    /**
     *  配置文件设置
     *
     * @param key
     * @param value
     * @return boolean
     */
    private static boolean setKey(String key, String value) {
        Properties properties = new Properties();
        File file = new File(FILE_NAME); // 其实有其他配置可以同意下yaml文件里面配置,然后这里面读取,好统一调配。
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file,true);
            properties.setProperty(key, value); // 存进map里面
            properties.store(fileWriter,""); // 将map对应的键值对写进输出流。这个comments 最后写入的时候是个注释
        } catch (IOException e) {
            // 卧槽我加入设置key,value失败,肯定调到这个逻辑
            return false;
        } finally {
            if (fileWriter != null) {  // 还是这样关比较好,万一报错就tm关不了
                try {
                    fileWriter.flush();
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

}

8.Archivo 

En Java, el objeto de archivo representa la representación abstracta de archivos y directorios .

 Caso: implementación recursiva de directorios de archivos transversales

public class FileDemo {
    public static void main(String[] args) {
        getChildrenFile("src",1);
    }


    // 递归则子文件所有目录
    public static void getChildrenFile(String fileName,int y){ // fileName 文件路径名,y 是目录等级
        File file = new File(fileName);
        StringBuffer stb = new StringBuffer();
        // 根据目录等级追加几条 "-"
        for (int i = 0; i < y; i++) {
            stb.append("-");
        }
        // 遍历子文件
        for (String name: file.list()) {
            System.out.println(stb + name); // 目录等级 + 文件路径名,并且换行
            String childrenName = fileName + "/"+name;
            if(new File(childrenName).isDirectory()){ // 判断子文件是否是递归,是的话仍执行
                getChildrenFile(childrenName,y+1); // 同样下一级目录等级 + 1
            }
        }
      }

    }

Referencias

Java IO Stream Explicación detallada (Byte Stream, Character Stream, Input Stream, Output Stream, Refresh)_Input Stream Output Stream Update Stream_Fat Brother's Blog-CSDN Blog

 Flujo de Java IO (¡súper detallado!)_Blog de un feliz puntero salvaje ~-CSDN Blog

Supongo que te gusta

Origin blog.csdn.net/Qhx20040819/article/details/132086878
Recomendado
Clasificación