Ghi và đọc file bằng ObjecInputStream,ObjecOutPutStream

Cách ghi file bẳng ObjectOutoutStream:

package test.lession3;

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.util.ArrayList;
import java.util.List;

public class ObjectOutputStreamExample {

	
	public static void main(String[] args) throws IOException {
//		Ghi dư liệu
		List<Student> list = new ArrayList<>();
		list.add(new Student("A", "Chung"));
		list.add(new Student("B", "Quynh"));
		list.add(new Student("C", "Mai"));
		FileOutputStream fileOutputStream = null;
		ObjectOutputStream objectOutputStream = null;
		try {
	fileOutputStream = new FileOutputStream("students.dat");//đặt tên là gì cũng đc
			objectOutputStream = new ObjectOutputStream(fileOutputStream);
			objectOutputStream.writeObject(list);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (fileOutputStream != null) {
				fileOutputStream.close();
			}
			if (objectOutputStream != null) {
				objectOutputStream.close();
			}
		}
	}

}

Cách đọc file bằng ObjectInputStream:


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.util.ArrayList;
import java.util.List;    

public class ObjectOutputStreamExample {
public static void main(String[] args) throws IOException {
//Đọc dữ liệu
    List<Student> list = new ArrayList<>();
    FileInputStream fileInputStream = null;
    ObjectInputStream objectInputStream = null;

    try {
        fileInputStream = new FileInputStream("students.dat");
        objectInputStream = new ObjectInputStream(fileInputStream);
        list = (List<Student>) objectInputStream.readObject();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        if (fileInputStream != null) {
            fileInputStream.close();
        }
        if (objectInputStream != null) {
            objectInputStream.close();
        }
    }
    System.out.println("Result: ");
    list.forEach((item) -> {
        System.out.println(item);
    });
}

}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Chào mừng bạn đến với blog của tôi! Đây là nơi tôi chia sẻ những trải nghiệm, suy nghĩ và kiến thức mà tôi học được trong cuộc sống và công việc. Hy vọng bạn sẽ tìm thấy điều gì đó hữu ích và thú vị tại đây.

Design a site like this with WordPress.com
Get started