[Java] Remember to add the object to the file in java – Append object to file exist in java


After all Read the objects from the file in java, there are many issues that you need to write more data on file. Usually we just declare

FileOutputStream f = new FileOutputStream(fileName,true);

But after many attempts I still do not. Search for a while, apart from the extra stuff 2 such is true, then we need to override the method writeStreamHeader as follows:

ObjectOutputStream oStream = new ObjectOutputStream(f) {
	protected void writeStreamHeader() throws IOException {
		reset();
	}
};

1. Quick Code to test

package vietSource.net.IOFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ReadWriteObject {

	public static void main(String[] args) {

		File f = new File("student.dat");
		FileOutputStream fo;
		ObjectOutputStream oStream = null;

		// ghi file lan 1
		try {
			fo = new FileOutputStream(f);
			oStream = new ObjectOutputStream(fo);

			oStream.writeObject(new MyStudent("pham ha", 22));
			oStream.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// ghi file lan 2
		try {
			fo = new FileOutputStream(f, true);
			oStream = new ObjectOutputStream(fo) {
				protected void writeStreamHeader() throws IOException {
					reset();
				}
			};
			oStream.writeObject(new MyStudent("nguyenvanquan7826", 22));
			oStream.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// doc file
		try {
			FileInputStream fis = new FileInputStream(f);
			ObjectInputStream inStream = new ObjectInputStream(fis);

			System.out.println(inStream.readObject());
			System.out.println(inStream.readObject());

			inStream.close();
		} catch (ClassNotFoundException e) {
			System.out.println("Class not found");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Error Read file");
			e.printStackTrace();
		}
	}
}

class MyStudent implements Serializable {
	String name;
	int age;

	public MyStudent(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String toString() {
		return "MyStudent [name=" + name + ", age=" + age + "]";
	}
}

2. Complete code should be used

Do not exist if no object file or files will be added error, therefore to ensure that all cases you see the following code:

package vietSource.net.IOFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ReadWriteObject {

	// kiem tra file co object hay khong
	public static boolean hasObject(File f) {
		// thu doc xem co object nao chua
		FileInputStream fi;
		boolean check = true;
		try {
			fi = new FileInputStream(f);
			ObjectInputStream inStream = new ObjectInputStream(fi);
			if (inStream.readObject() == null) {
				check = false;
			}
			inStream.close();

		} catch (FileNotFoundException e) {
			check = false;
		} catch (IOException e) {
			check = false;
		} catch (ClassNotFoundException e) {
			check = false;
			e.printStackTrace();
		}
		return check;
	}

	public static void write(MyStudent s) {
		try {

			File f = new File("student.dat");
			FileOutputStream fo;
			ObjectOutputStream oStream = null;

			// neu file chu ton tai thi tao file va ghi binh thuong
			if (!f.exists()) {
				fo = new FileOutputStream(f);
				oStream = new ObjectOutputStream(fo);
			} else { // neu file ton tai

				// neu chua co thi ghi binh thuong
				if (!hasObject(f)) {
					fo = new FileOutputStream(f);
					oStream = new ObjectOutputStream(fo);
				} else { // neu co roi thi ghi them vao

					fo = new FileOutputStream(f, true);

					oStream = new ObjectOutputStream(fo) {
						protected void writeStreamHeader() throws IOException {
							reset();
						}
					};
				}
			}

			oStream.writeObject(s);
			oStream.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void read() {
		try {
			File f = new File("student.dat");
			FileInputStream fis = new FileInputStream(f);
			ObjectInputStream inStream = new ObjectInputStream(fis);
			Object s;
			int i = 0;
			while (true) {
				s = inStream.readObject();
				System.out.println(++i + ":" + s.toString());
			}
		} catch (ClassNotFoundException e) {
		} catch (IOException e) {
		}
	}

	public static void main(String[] args) {

		// ghi sinh vien 1
		write(new MyStudent("nguyenvanquan7826", 22));

		// ghi tiep sinh vien 2
		write(new MyStudent("phamha", 22));

		// doc file
		read();

	}
}

class MyStudent implements Serializable {
	String name;
	int age;

	public MyStudent(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String toString() {
		return "MyStudent [name=" + name + ", age=" + age + "]";
	}
}