Học code Java

Học code Java về thao tác với File nhị phân

Trong bài viết trước các bạn đã được luyện tập với thao tác file văn bản. Trong bài viết này chúng ta cùng học code Java cơ bản về các thao tác với file nhị phân nhé!

Học code Java – thao tác với file nhị phân

Đề bài

Để luyện tập các thao tác với file nhị phân chúng ta hãy cùng làm các bài tập sau nhé

Bài tập 1:

  • Viết chương trình copy dữ liệu từ file a.txt chứa các dữ liệu số sang b.txt sử dụng file nhị phân

Bài tập 2:

  • Viết chương trình copy dữ liệu từ file a.txt chứa các đối tượng sang b.txt sử dụng file nhị phân

Bài tập 3:

  • Viết chương trình ghi danh sách các sinh viên ra file student.txt
    • Tạo lớp Student có các thuộc tính: mã sinh viên, họ tên, quê quán
    • Thực hiện việc ghi danh sách sinh viên ra file student.txt

Lời giải

Cùng tìm lời giải cho các bài tập trên ở đây nha!

Bài tập 1:

  • Viết chương trình copy dữ liệu từ file a.txt chứa các dữ liệu số sang b.txt sử dụng file nhị phân
  • Chương trình:
package com.company;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("source.txt");
            FileOutputStream fos = new FileOutputStream("destination.txt");
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) > 0) {
                fos.write(bytes, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Bài tập 2:

  • Viết chương trình copy dữ liệu từ file a.txt chứa các đối tượng sang b.txt sử dụng file nhị phân
  • Chương trình:

Student.class

package com.company;

import java.io.Serializable;

public class Student implements Serializable {
    private String id;

    private String name;

    private String address;

    public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public Student(String id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

StudentMain.class

package com.company;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class StudentMain {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("001", "Nguyen Van A", "Ho Chi Minh"));
        students.add(new Student("002", "Nguyen Van B", "Ha Noi"));
        students.add(new Student("003", "Nguyen Van C", "Hue"));
        students.add(new Student("004", "Nguyen Van D", "Da Nang"));
        writeToFile(students);
        try {
            InputStream inputStream = new FileInputStream("student.txt");
            ObjectInputStream ois = new ObjectInputStream(inputStream);
            OutputStream os = new FileOutputStream("copy-of-student.txt");
            ObjectOutputStream oos = new ObjectOutputStream(os);
            List<Student> studentCopy = (List<Student>) ois.readObject();
            oos.writeObject(studentCopy);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void writeToFile(List<Student> students) {
        try {
            OutputStream os = new FileOutputStream("student.txt");
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(students);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Bài tập 3:

  • Viết chương trình ghi danh sách các sinh viên ra file student.txt
    • Tạo lớp Student có các thuộc tính: mã sinh viên, họ tên, quê quán
    • Thực hiện việc ghi danh sách sinh viên ra file student.txt
  • Chương trình:

Student.class

package com.company;

public class Student {
    private String id;

    private String name;

    private String address;


    public Student() {
    }

    public Student(String id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

MainStudent.class

package com.company;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class MainStudent {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("001", "Nguyen Van A", "Ho Chi Minh"));
        students.add(new Student("002", "Nguyen Van B", "Ha Noi"));
        students.add(new Student("003", "Nguyen Van C", "Hue"));
        students.add(new Student("004", "Nguyen Van D", "Da Nang"));
        readObjectFromFile();
        writeToBinaryFile(students);
    }

    private static List<Student> readObjectFromFile() {
        List<Student> studentListFromFile = new ArrayList<>();
        try {
            InputStream is = new FileInputStream("student.txt");
            ObjectInputStream ois = new ObjectInputStream(is);
            studentListFromFile = (List<Student>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return studentListFromFile;
    }

    private static void writeToBinaryFile(List<Student> students) {
        try {
            OutputStream os = new FileOutputStream("student.txt");
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(students);
            oos.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

KHÓA HỌC LẬP TRÌNH CĂN BẢN CHO NGƯỜI MỚI BẮT ĐẦU!

Bài viết liên quan

Trả lời

Email của bạn sẽ không được hiển thị công khai.

Tài liệu + Khóa học lập trình FREE
Tài liệu + Khóa học lập trình FREE

DMCA.com Protection Status