[Java] Ghi Thêm đối Tượng Vào File Trong Java – Append Object To File ...

  • Bài viết
  • Hỏi đáp
Tạo bài viết Đăng ký Đăng nhập Code24h.com Blog 01/10/2018, 22:32 [Java] Ghi thêm đối tượng vào file trong java – Append object to file exist in java

[Java] Ghi thêm đối tượng vào file trong java – Append object to file exist in java Tháng Mười Hai 17, 2014 nguyenvanquan7826 LT Java 6 responses Sau bài Đọc ghi đối tượng từ file trong java, có nhiều vấn đề mà mình cần ghi ...

[Java] Ghi thêm đối tượng vào file trong java – Append object to file exist in java

Tháng Mười Hai 17, 2014 nguyenvanquan7826 LT Java 6 responses

Sau bài Đọc ghi đối tượng từ file trong java, có nhiều vấn đề mà mình cần ghi thêm dữ liệu vào file. Thông thường chúng ta chỉ cần khai báo

FileOutputStream f = new FileOutputStream(fileName,true);

Tuy nhiên sau nhiều lần thử mình vẫn chưa làm được. Tìm kiếm một hồi thì ngoài việc thêm đối thứ 2 là true như trên thì chúng ta cần viết đè phương thức writeStreamHeader như sau:

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

1. Code nhanh để 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. Code hoàn chỉnh nên dùng

Do nếu chưa tồn tại file hoặc file chưa có object thì sẽ bị lỗi ghi thêm, do đó để đảm bảo mọi trường hợp bạn hãy xem code sau:

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 + "]"; } } Bình luận về bài viết này

Hoàng Hải Đăng

24 chủ đề

7226 bài viết

Có thể bạn quan tâm
  • 1 Fix error xamp 403 Forbidden
  • 2 [Thuật toán] Tìm đường đi ngắn nhất Dijkstra, Floyd
  • 3 [Android] RecyclerView trong Android
  • 4 [wordpress] Tạo Child Theme
  • 5 [C/C++]get() and fget() in C/C++ – Cảnh báo khi dùng gets() – Warning when use gets()
  • 6 Error XAMPP : Mysql # 2002 – No such file or directory
  • 7 [Android – Java] Chương trình máy tính bỏ túi trên Android – Calculator Program on Android
  • 8 [Java] Sử dụng interface
  • 9 [Thuật toán] Sắp xếp trộn – Merge Sort
  • 10 [C/C++] Ví dụ đọc ghi kiểu dữ liệu cấu trúc vào file kiểu nhị phân trong C
0 Các chủ đề đang được quan tâm phần mềm lập trình php | lập trình web php + mysql | khóa học lập trình php | tự học lập trình php | học php cơ bản thachpham | Code24h | Cho thuê phòng trọ hà nội | Cho thuê phòng trọ bình thạnh | Cho thuê phòng trọ | Cho thuê nhà trọ Đăng ký

Đăng ký nhận thông báo

Các bài học thú vị sẽ được gửi đến inbox của bạn

HỖ TRỢ HỌC VIÊN
  • Các câu hỏi thường gặp
  • Điều khoản sử dụng
  • Chính sách và quy định
  • Chính sách bảo mật thanh toán
  • Hỗ trợ học viên: [email protected]
  • Báo lỗi bảo mật: [email protected]
VỀ CODE24H
  • Giới thiệu Code24h
  • Cơ hội nghề nghiệp
  • Liên hệ với chúng tôi
HỢP TÁC VÀ LIÊN KẾT
  • Đăng ký giảng viên
  • Giải pháp e-learning
  • Chương trình đại lý
  • Chương trình Affiliate
KẾT NỐI VỚI CHÚNG TÔI
TẢI ỨNG DỤNG TRÊN ĐIỆN THOẠI

CCode 24h, code mọi lúc, mọi nơi

© Copy right 2018 - 2026

Từ khóa » Ghi File đối Tượng Trong Java