[Java] Read recorded in the Java Object – Read Write Object in Java
To read recorded in the Java Object in the Object class in which we need to communicate java.io.Serializable
A simple example of reading record 1 Object MyStudent as follows:
package VietSource.net.File; // cac ban nho thay package cho phu hop import java.io.FileInputStream; 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){ MyStudent myStudent = new MyStudent(); // tao doi tuong myStudent //Ghi Object vao file try { // dat try cacth de tranh ngoai le khi tao va viet File FileOutputStream f = new FileOutputStream("student.dat"); // tao file f tro den student.dat ObjectOutputStream oStream = new ObjectOutputStream(f); // dung de ghi theo Object vao file f oStream.writeObject(myStudent); // ghi MyStudent theo kieu Object vao file oStream.close(); } catch (IOException e) { System.out.println("Error Write file"); } // doc Object tu file MyStudent ms = null; try { // dat try cacth de tranh ngoai le khi tao va doc File FileInputStream f = new FileInputStream("student.dat"); // tao file f tro den student.dat ObjectInputStream inStream = new ObjectInputStream(f); // dung de doc theo Object vao file f // dung inStream doc theo Object, ep kieu tra ve la MyStudent ms = (MyStudent) inStream.readObject(); inStream.close(); } catch (ClassNotFoundException e) { System.out.println("Class not found"); } catch (IOException e) { System.out.println("Error Read file"); } // Xuat KQ System.out.println("My name is " + ms.name + ". I am " + ms.age + " years old"); } } class MyStudent implements Serializable{ String name = "Nguyen Van Quan"; int age = 21; }
Result: My name is Nguyen Van Quan. I am 21 years old
Noted: When you open the file student.dat you will find out this kind of data:
A more specific example of how to read and write, in this example 1 Student class attribute contains the name and age and the get method, set the value of their. A ProcessStudent class includes methods allow the student to enter from the keyboard, recorded on the student file, read from files by type Object and finally display the information read. In the code was explained quite clearly:
package VietSource.net.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Scanner; public class IOFileObject_Student { public static void main(String args[]) throws Exception { ProcessStudent ps = new ProcessStudent(); // tao doi tuong cua lop ProcessStudent Student[] student1 = null, student2 = null; // tao 2 doi tuong student student1 = ps.creat(); // nhap student ps.write(student1); // viet vao file student2 = ps.read(); // doc tu file ps.show(student2); //hien thi kq } } class Student implements Serializable { // Serializable dung de ghi va doc theo Object private static final long serialVersionUID = 1L; // ID of Serializable private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } // cac ham get, set gia tri cac bien 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; } } // class xu ly thong tin class ProcessStudent { public Student[] creat() { // Input the data from Keyboard int n; Scanner scan = new Scanner(System.in); System.out.print("Enter number of student: "); n = Integer.parseInt(scan.nextLine()); //nhap so sinh vien Student[] student = new Student[n]; for (int i = 0; i < n; i++) { System.out.print("Enter name: "); // nhap ten sv thu i String name = scan.nextLine(); System.out.print("Enter age: "); // nhap tuoi int age = Integer.parseInt(scan.nextLine()); // tranh troi lenh nhu khi dung scan.nextInt() student[i] = new Student(name, age); // khoi tao doi tuong Student thu i } scan.close(); return student; } public void write(Student[] student) { //ghi theo Object try { // dat try cacth de tranh ngoai le khi tao va ghi File FileOutputStream f = new FileOutputStream("student.dat"); // tao file f tro den student.dat ObjectOutputStream oStream = new ObjectOutputStream(f); // dung de ghi theo Object vao file f oStream.writeObject(student); // ghi student theo kieu Object vao file oStream.close(); } catch (IOException e) { System.out.println("Error Write file"); } } public Student[] read() { // doc theo Object Student[] student = null; try { // dat try cacth de tranh ngoai le khi tao va doc File FileInputStream f = new FileInputStream("student.dat"); // tao file f tro den student.dat ObjectInputStream inStream = new ObjectInputStream(f); // dung de doc theo Object vao file f // dung inStream doc theo Object, ep kieu tra ve la Student student = (Student[]) inStream.readObject(); inStream.close(); } catch (ClassNotFoundException e) { System.out.println("Class not found"); } catch (IOException e) { System.out.println("Error Read file"); } return student; } public void show(Student[] student) throws Exception { //In data doc duoc tu file ra man hinh try { for (int i = 0; i < student.length; i++) { System.out.println((i + 1) + " : My name is " + student[i].getName() + ". I am " + student[i].getAge() + " years old"); } } catch (NullPointerException e) { System.out.println("File Empty"); } } }
Read more: Remember to add the object to the file in java
Thank you to read your code is easy to understand
Thank you for your interest in blog. Chúc bạn học tập tốt 😀
thank you very much !!!!! ^ _ ^
Glad it helped to be something for you. 🙂
Very thanks ! I was to learn . .
Visit Blog frequently offline,
Written!, solution. But in the closing flow should finally put in your .As code on the following assume that try threading dies will not be closed.
try{
//
}catch(Exception e){
}finally {
//close() stream;
}
Thanks for very useful comments of you.
But so again try to catch more 1 Again a bit complicated, so I do not :). Want to keep it simple as possible.
Cảm ơn a rất nhiều ạ.Nhờ bài của a mà e vỡ ra nhiều điều.Thanks so much !!!!!
Cho em hỏi là nếu làm với ArrayList thì làm thế nào ạ ?
ArrayList bạn có thể ghi thẳng cả list hoặc dùng for để ghi từng Object trong list vào file.
file student.dat ở thư mục nào hả anh?
Nó nằm ở thư mục project
Cảm ơn bài viết của cậu. Tớ có câu hỏi: tớ viết được lớp SinhVien.java, Course.java now want to write class, the class contains students how Course ?
You do the same students are đk
Let me ask what the original file is the file extension à .
.dat file you open in Nodepad out strange characters .
Standards and. Remember, it's an object that. Where There must read your text. Same exe, know that nothing. Now right click the .exe file and select open with any notepad, it too.
His dear friend for his hoi.Vay recorded only when the file object to the new class implements Serializable only need to correct it ban.Vay saved to the database when the class implements Serializable need not because the database is saved each colurm not follow fish 1 object.Ngoai to the public in such cases, we must Serializable.Nhung class implements any case should not class implements Serializable.
When you save a database there is no need.
In his TH want to compress it to do something, as recorded in this file
vậy làm sao biết thông tin ghi vào có đúng k?
Kiểm tra bằng cách đọc lại file 🙂
ví dụ như có đối tuong A và trong A có arrayList vậy thì khi đọc/write mảng dữ liệu kiểu B thì có thể đọc cho A được không ?
I have not quite understand what you mean.
private static final long serialVersionUID = 1L;
Anh cho em hỏi hằng này nó dùng để làm gì ạ ? thiếu nó thì cảnh báo nhưng có rồi không biết sử dụng để làm gì.
Cái này anh cũng không biết, chưa tìm hiểu 🙂
Sao ko làm đọc ghi từng đối tượng đi ạ ????
Cái này dễ chứ cái kia e thấy phức tạp hơn ở phần đọc file đó ạ
Code rất rõ ràng và dễ hiểu. cảm ơn ad nhiều!!