IO stream & Properties configuration file

Table of contents

input stream and output stream

File file addition and deletion

Commonly used IO stream classes and their classifications

FileInputStream/FileOutputStream

ObjectInputStream/ObjectOutputStream

BufferedInputStream/BufferedOutputStream

FileReader/FileWriter

BufferedReader/BufferedWriter

InputStreamReader/InputStreamWriter

Properties read configuration file


input stream and output stream

Before learning IO programming, you need to understand the relationship between the input stream and the output stream: the input stream and the output stream are relative to the program, as shown in the following figure:

File file addition and deletion

File Create a new file There are three common ways to construct a file object:

  • public File(String filePath)
  • public File(File parent,String child)
  • public File (String parent, String child)
    choose one of them to create a file under the specified path through the createNewFile method, and create a directory through mkDir (create a single-layer directory) and mkDirs (create a multi-layer directory):
    @Test
    public void createFile() throws IOException {
        String filePath = "E:\\IOStream\\FileInputStreamFiles\\hello.txt";
        String filePathOfDir = "E:\\IOStream\\FileInputStreamFiles\\helloDir";
        File file = new File(filePath);
        File fileDir = new File(filePathOfDir);
        try {
            if(file.createNewFile()) {  //返回值boolean类型
                System.out.println("创建成功");
            } else {
                System.out.println("创建失败");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (fileDir.mkdir()) {
            System.out.println("目录创建成功");
        } else {
            System.out.println("目录创建失败");
        }
    }

Delete deletes empty directories or files

Delete the files and directories created above:

@Test
public void deleteFile() {
    String filePath = "E:\\IOStream\\FileInputStreamFiles\\hello.txt";
    String pathOfDir = "E:\\IOStream\\FileInputStreamFiles\\helloDir";
    File file = new File(filePath);
    File fileDir = new File(pathOfDir);
    if(file.delete()) { //删除文件
        System.out.println(file.getName() + "文件删除成功");
    } else {
        System.out.println(file.getName() + "文件删除失败");
    }
    if(fileDir.delete()) { //删除目录
        System.out.println(fileDir.getName() + "目录删除成功");
    } else {
        System.out.println(fileDir.getName() + "目录删除失败");
    }
}

Commonly used IO stream classes and their classifications

In a Java program, input streams and output streams are divided into byte input/output streams and character input/output streams. The byte input and output streams use InputStream and OutputStream as their abstract base classes; the character input and output streams use Reader and Writer as their abstract base classes. Common IO stream classes and their inheritance relationships are as follows:

 FileInputStream/FileOutputStream

Read files using byte input stream FileInputStream

import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.IOException;
public void readFile() {
    String filePath = "E:\\IOStream\\FileInputStreamFiles\\hello.txt";
    FileInputStream fileInputStream = null;
    /*使用read一次读取单个字节
    try {
        int byte_ = 0;
        fileInputStream = new FileInputStream(filePath);
        while ((byte_ = fileInputStream.read()) != -1) {
            System.out.print((char) byte_);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            fileInputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }*/
    //使用字节数组方式一次读取byte.length个字节
    try {
        byte[] byte_ = new byte[4];
        int readLength = 0;
        fileInputStream = new FileInputStream(filePath);
        while ((readLength = fileInputStream.read(byte_)) != -1) {   //read(byte)返回读取到的字节个数
            System.out.println(new String(byte_, 0, readLength));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            fileInputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Write files using the byte output stream FileOutputStream

import org.junit.jupiter.api.Test;

import java.io.FileOutputStream;
import java.io.IOException;
/**
 * 使用FileOutputStream写文件
 * 创建FileOutputStream时,如果没有这个文件会自动创建,如果有且append属性为false时会清空该文件
 * 在写入文件后没有关闭继续写时,会继续将内容追加文件末尾
 */
@Test
public void writeFile() {
    String filePath = "E:\\IOStream\\FileInputStreamFiles\\hello.txt";
    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(filePath, false);//true代表再次写入数据时追加原数据
//            fileOutputStream.write('ad');//向hello.txt中写入单个字节
        String str = "hello,world";
        //getBytes将字符转换成一个字节数组
        fileOutputStream.write(str.getBytes());
        System.out.println("写入成功");
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Application: copy files

/**
 * 使用输入输出流完成文件的拷贝,在读/写文件时使用字节数组提高读取和写入效率
 */
@Test
public void copy() {
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;

    try {
        fileInputStream = new FileInputStream("E:\\IOStream\\FileInputStreamFiles\\Copy.txt");
        fileOutputStream = new FileOutputStream("E:\\IOStream\\FileInputStreamFiles\\copyFinish.txt");
        int temp = 0;
        int readLength = 0;
        //创建字符数组,提高文件的读取效率
        byte[] byte_ = new byte[1024];
        while ((readLength = fileInputStream.read(byte_)) != -1) {
            fileOutputStream.write(byte_, 0, readLength);
        }
        System.out.println("复制完成");
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if(fileInputStream != null) {
                fileInputStream.close();
            }
            if(fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

ObjectInputStream/ObjectOutputStream

Similar to FileReader and FileWriter, object input/output streams ObjectInputStream and ObjectOutputStream are also processing streams. It is used to save the type and value of data, and can restore the metadata type and value according to a specific sequence.
Serialization and deserialization:

  • Serialization refers to saving the value and data type of data when saving data
  • Deserialization refers to restoring the value and data type of data when restoring data

Use object input and output streams to read and write files:

//Dog类
package objectstream;

import java.io.Serializable;
/**
 * Dog类实现了Serializable接口,表明其可以被序列化
 */
public class Dog implements Serializable {
    private String name;//String类默认实现了Serializable接口
    private int age;
    public Dog(String name,int age) {
        this.name = name;
        this.age = age;
    }
    public String toString() {
        return "[" +  this.name + " " + this.age +"]";
    }
}

//ObjectOutputStream_类
public class ObjectOutputStream_ {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("E:\\IOStream\\objectStream\\object.dat"));
            //序列化对应的数据时,要求该数据的数据类型是可序列化的,即实现了Serializable或Externalizable接口
            oos.writeInt(7);
            oos.writeUTF("hello");
            oos.writeObject(new Dog("小黑",7));
            System.out.println("序列化完成(文件写入完成)");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (oos != null) {
                try {       //序列化结束后关闭流
                    oos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}

//ObjectInputStream_类
import java.io.*;
public class ObjectInputStream_ {
    public static void main(String[] args) {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("E:\\IOStream\\objectStream\\object.dat"));
            System.out.println(ois.readInt());
            System.out.println(ois.readUTF());
            System.out.println(ois.readObject());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ois != null) {  //结束后记得关闭流
                try {
                    ois.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

Notes on the use of object input and output streams:

  • Serialized files are stored in (.dat) format
  • The order of serialization and deserialization of data must be the same, otherwise java.io.OptionalDataException will be thrown
  • Serialized or deserialized objects need to implement the Serializable or Externalizable interface
  • It is recommended to add SerialVersionUID to the serialized class to improve version compatibility
  • When serializing member properties in a class, all properties except those modified by static and transient will be serialized
  • When the serialized custom object is taken out, if you want to call the custom method in the custom object, you need to perform a downcast and ensure that the custom object can be accessed

BufferedInputStream/BufferedOutputStream

Note:
After using the BufferedOutputStream to process the stream to output the file content, the file should be closed, otherwise the content cannot be written successfully.

FileReader/FileWriter

Read a file using a character input stream FileReader:

import java.io.fileReader;

public class BufferedReader {

    public static void main(String[] args) {
        FileReader fileReader = null;
        try {
            fileReader = new FileReader("E:\\IOStream\\FileInputStreamFiles\\temp.txt");
            char[] chars = new char[1024];
            int readLen = 0;
            while((readLen = fileReader.read(chars)) != -1) {
                System.out.print(new String(chars,0,readLen));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

Write a file using a character output stream FileWriter:

  • Note:
    When using FileWriter to write files, only when the file is closed after writing is completed can the content be successfully written. When creating a FileWriter object, if you do not specify the append property as false, then when the file is opened for writing, the data in the original file will be overwritten.
import org.juint.jupiter.api.test;

@Test
public void writeFile() {
    FileWriter fileWrtier = null;
    String path = "E:\\IOStream\\FileInputStreamFiles\\temp.txt";
    try {
        fileWrtier = new FileWriter(path);
        fileWrtier.write("你好,川藏318");
        //fileWrtier.write(int c);
        //fileWrtier.write(str,start,end);
        //fileWrtier.write(char[] chars,start,end);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            fileWrtier.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

BufferedReader/BufferedWriter

Node flow and processing flow:

  • Node stream can read data from a specific data source, such as FileReader, FIleWriter
  • The processing stream is also a packaging stream, which is connected to the existing stream to provide more powerful read and write functions for the program, such as BufferedReader, BufferedWriter

BufferedWriter handles streams for writing files:

  • Note:
    When using BufferedReader to write files, only when the file is closed after the writing is completed can the content be successfully written. When creating a BufferedReader object, if you do not specify the append property as false, then when the file is opened for writing, the data in the original file will be overwritten.
    When using BufferedReader and BufferedWriter to copy files, avoid copying binary files (sound, image, video, word, pdf), and an exception will occur when the copy is completed and opened.
public class BufferedWriter__ {
    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = null;
        //设置append属性:在传入BufferedWriter对象中封装的Writer对象中指定
        bufferedWriter = new BufferedWriter(new FileWriter("E:\\IOStream\\FileReaderFiles\\files\\temp.java",true));
        bufferedWriter.write("hello");
        bufferedWriter.newLine();//换行
        if(bufferedWriter != null) {
            bufferedWriter.close();
        }
    }
}

InputStreamReader/InputStreamWriter

InputStreamReader and InputStreamWriter are also called conversion streams, which can convert byte processing streams into character processing streams and specify specific encoding formats .

Lead: When using the byte processing stream to read gbk encoded files, Chinese garbled characters appear. In order to solve this problem, you can use InputStreamReader to package the corresponding byte processing stream into a character processing stream, and specify a specific encoding format for reading.

public class BufferedReader_ {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("E:\\java代码\\IO_Stream_21\\io\\read.txt"),"GBK"));//在进行转换时指定待读取文件的编码格式,防止出现乱码问题
        String str = null;
        while((str = br.readLine()) != null) {
            System.out.println(str);
        }
    }
}
public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:\\java代码\\IO_Stream_21\\io\\read.txt",true),"gbk");//指定的编码格式进行内容的写入
        osw.write(" hello世界 ");
        System.out.println("文件写入成功");
        osw.close();
    }
}

Precautions:

Conversion stream InputStreamReader and OutputStreamWriter can solve the problem of garbled characters, but you should pay attention to the corresponding encoding format when using it.

Properties read configuration file

The file with the suffix .properties is usually used as a Java configuration file, and the data format in the file is stored in the form of key-value pairs. Using the properties configuration file improves the flexibility of the program.

Operations related to using Properties to manipulate files:

public class Properties_ {
    public static void main(String[] args) {
        Properties pro = new Properties();
        try {
            pro.load(new FileInputStream("src\\mysql.properties"));
            System.out.println(pro.getProperty("username"));
            System.out.println(pro.getProperty("ip"));
            System.out.println(pro.get("username"));
            pro.setProperty("active", "good");
            pro.setProperty("state", "stable");
            pro.setProperty("active", "silence");
            pro.setProperty("uio", "玛利亚");
            pro.store(new FileOutputStream("src\\mysql.properties"), "good");
            System.out.println(pro.getProperty("uio"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Precautions:

Save the information to the configuration file in idea. If the information contains Chinese, it will be stored as the corresponding unicode encoding.

Guess you like

Origin blog.csdn.net/weixin_64450588/article/details/128299181