Java files read and write multiple objects

Before sorting out file read and write objects, review the contents of file read and write:

Character stream and byte stream

1. Character stream

In the process of transmission, the most basic unit of transmitted data is the stream of characters

Read file contents through BufferedReader:

public static void readFile() throws IOException {
	Path path = Paths.get("data.txt");
	BufferedReader reader = Files.newBufferedReader(path);
	String lineContent = reader.readLine();
	while (lineContent != null) {
		System.out.println(lineContent);
		lineContent = reader.readLine();
	}
	reader.close();
}

BufferedReader: extended from the Reader class, it provides a general buffering method for text reading to improve efficiency, and provides a very practical readLine() method

Write to the file through BufferedWriter:

public static void writeFile(String[] data) throws IOException {
	Path path = Paths.get("data.txt");
	BufferedWriter writer = Files.newBufferedWriter(path);
	for (int i=0;i<data.length;i++) {
		writer.write(data[i]);
		writer.newLine();
	}
	writer.close();
}

2. Byte stream

In the process of transmission, the most basic unit of transmitted data is the stream of bytes

Read file contents through BufferedInputStream:

public static void readFile() throws IOException {
	FileInputStream file = new FileInputStream("data.txt");
	BufferedInputStream reader = new BufferedInputStream(file);
	byte[] buff = new byte[MAX_SIZE];
	while ((len  = reader.read(buff)) != -1) {
		System.out.println(new String(buff, 0, len));
	}
	reader.close();
	file.close();
}

new String(byte bytes[], int offset, int length, String charsetName); : Encodes a binary array by specifying a character set and converts it to string form.

Write to the file through BufferedOutputStream:

public void writeFile(String data) throws IOException {
	FileOutputStream file = new FileOutputStream("data.txt");
	BufferedOutputStream writer = new BufferedOutputSream(file);
	writer.write(data.getBytes());
	writer.close();
	file.close();
}

BufferedInputStream and BufferedOutputStream: a stream that improves efficiency by encapsulating other streams, so you need to instantiate another stream before use.

3. Difference between character stream and byte stream

In essence, whether reading or writing data, binary is accessed in bytes. Byte stream is to directly read or write the file content in binary form. If we want to know the read content, we need to specify an encoding method. When writing, we need to convert it to byte type. The character stream has its own encoding, so we don't need to convert it manually when reading and writing, and the basic unit is the size of the character.

Object read and write

To read and write files to an object, you need to make the object implement an interface Serializable first

Serializable is a semantic level interface defined in the java.io package to implement the serialization of classes. The serializable interface does not have any methods or fields, but is only used to identify serializable semantics. The class that implements the serializable interface can be represented as a byte sequence, which includes the data of the object, information about the type of the object and the type of data stored in the object. It can be converted into a byte stream by ObjectOutputStream, and can also be parsed into an object by ObjectInputStream.

1. Read an object

public void readObject() throws IOException, ClassNotFoundException {
	FileInputStream file = new FileInputStream(new File("data.txt"));
	ObjectInputStream reader = new ObjectInputStream(file);
    YourClassName Cls = (YourClassName) reader.readObject();
    file.close();
    reader.close();
}

2. Write an object

public void writeObject(YourClassName Data) throws IOException {
	FileOnputStream file = new FileOnputStream(new File("data.txt"));
	ObjectOnputStream writer = new ObjectOnputStream(file);
    writer.writeObject(Data);
    file.close();
    reader.close();
}

3. Read multiple objects

public List readMulObject() throws IOException {
    List<Student> lst = new ArrayList<>();
    FileInputStream file = new FileInputStream(new File("data.txt"));
	ObjectInputStream reader = new ObjectInputStream(file);
    while (true) {
        try {
            YourClassName Cls = (YourClassName) reader.readObject();
            lst.add(Cls);
        } catch (EOFException e) {
        	System.out.println("Read complete");
        	break;
        }
    }
   	file.close();
   	reader.close();
    return lst;
}

4. Write multiple objects

public void writeFile(List<YourClassName> lst) throws IOException {
	FileOutputStream file = new FileOutputStream(new File("data.txt"));
    ObjectOutputStream writer = new ObjectOutputStream(file);
    for (YourClassName Cls : lst) {
        writer.writeObject(Cls);
    }
    writer.close();
}

There is a problem here. When writing objects, they will be written from the beginning of the file by default, which will overwrite the original contents of the file. If you want to add a write to the back of the file, you need FileOutputStream file = new FileOutputStream(new File("data.txt"), 1) but there will be another problem: each time you open the file, the program will add an ACED 0005 field before writing information by default, but when reading, it will mistakenly think it is a part of the object, resulting in parsing errors. At present, I haven't found a perfect solution to this problem. The current measure is to use the List to take out all the contents before writing the file, then add all the written information to the List, and then store the whole List in the file.

Tags: Java Back-end

Posted on Sun, 05 Dec 2021 03:27:04 -0500 by RockRunner