By GokiSoft.com| 10:05 13/08/2021|
Java Advanced

[Share Code] Tìm hiểu File - FileInputStream & FileOutputStream - BufferedInputStream & BufferedOutStream - ObjectInputStream & ObjectOutputStream - Lập trình Java nâng cao

#Student.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson03;

import java.io.Serializable;

/**
 *
 * @author Diep.Tran
 */
public class Student implements Serializable{
    String fullname, gender, address, rollno;
    int age;

    public Student() {
    }

    public Student(String fullname, String gender, String address, String rollno, int age) {
        this.fullname = fullname;
        this.gender = gender;
        this.address = address;
        this.rollno = rollno;
        this.age = age;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddress() {
        return address;
    }

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

    public String getRollno() {
        return rollno;
    }

    public void setRollno(String rollno) {
        this.rollno = rollno;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "fullname=" + fullname + ", gender=" + gender + ", address=" + address + ", rollno=" + rollno + ", age=" + age + '}';
    }
    
    public String getFileLine() {
        return fullname + ", " + gender + ", " + address + ", " + rollno + ", " + age + "\n";
    }
    
    public void parseFileLine(String line) {
        String[] params = line.split(", ");
        fullname = params[0];
        gender = params[1];
        address = params[2];
        rollno = params[3];
        age = Integer.parseInt(params[4]);
    }
}


#Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package java2.lesson03;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class Main {

    public static void main(String[] args) {
        //testFile();
        //Test chuong trinh nghi file
        //saveFile();
        //saveFile2();
        //readFile();
        //readFile2();
        //Viet chuong trinh quan ly sinh vien -> luu thong tin sinh vien vao file
        //saveStudents();
        //readStudents();
        //saveStudents2();
        readStudents2();
    }
    
    static void readStudents2() {
        List<Student> studentList = new ArrayList<>();
        
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            fis = new FileInputStream("students.dat");
            
            ois = new ObjectInputStream(fis);
            
            studentList = (List<Student>) ois.readObject();
            
            for (Student student : studentList) {
                System.out.println(student);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    static void saveStudents2() {
        //Viet chuong trinh nhap thong tin sinh vien
        List<Student> studentList = new ArrayList<>();
        //Fake data
        studentList.add(new Student("A", "Nam", "Ha Noi", "R001", 18));
        studentList.add(new Student("B", "Nu", "Ninh Binh", "R002", 19));
        studentList.add(new Student("C", "Nu", "Thai Binh", "R003", 22));
        studentList.add(new Student("D", "Nam", "Nam Dinh", "R004", 32));
        studentList.add(new Student("E", "Nam", "Ha Nam", "R005", 12));
        
        //Luu file nhi phan
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        
        try {
            fos = new FileOutputStream("students.dat");
            
            oos = new ObjectOutputStream(fos);
            
            oos.writeObject(studentList);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
    }
    
    static void readStudents() {
        List<Student> studentList = new ArrayList<>();
        
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        
        try {
            reader = new FileReader("students.txt");
            bufferedReader = new BufferedReader(reader);
            
            String line;
            while((line = bufferedReader.readLine()) != null) {
                if(!line.isEmpty()) {
                    //Phan tich chuoi
                    Student std = new Student();
                    std.parseFileLine(line);
                    
                    studentList.add(std);
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        for (Student student : studentList) {
            System.out.println(student);
        }
    }
    
    /**
     * Save: students.txt
     */
    static void saveStudents() {
        //Viet chuong trinh nhap thong tin sinh vien
        List<Student> studentList = new ArrayList<>();
        //Fake data
        studentList.add(new Student("A", "Nam", "Ha Noi", "R001", 18));
        studentList.add(new Student("B", "Nu", "Ninh Binh", "R002", 19));
        studentList.add(new Student("C", "Nu", "Thai Binh", "R003", 22));
        studentList.add(new Student("D", "Nam", "Nam Dinh", "R004", 32));
        studentList.add(new Student("E", "Nam", "Ha Nam", "R005", 12));
        
        //Save File
        FileOutputStream fos = null;

        try {
            //true -> noi them, false -> ghi de.
            fos = new FileOutputStream("students.txt", false);

            //Giai phap luu file nhu the???
            for (Student student : studentList) {
                String line = student.getFileLine();
                //save line => vao file
                byte[] data = line.getBytes("utf8");
                fos.write(data);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    static void readFile2() {
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        
        try {
            reader = new FileReader("vidu.txt");
            bufferedReader = new BufferedReader(reader);
            
            String line;
            while((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
    }
    
    static void readFile() {
        FileInputStream fis = null;
        
        try {
            fis = new FileInputStream("vidu.txt");
            
            //Doc noi dung chuong trinh
            StringBuilder builder = new StringBuilder();
            int code;
            
            while((code = fis.read()) != -1) {
                builder.appendCodePoint(code);
            }
            
            System.out.println(builder.toString());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    static void saveFile2() {
        FileOutputStream fos = null;
        //Khi nhap string tu ban phim -> save vao file. Ket thuc ghi khi chuoi vao la chu N
        Scanner scan = new Scanner(System.in);

        try {
            //true -> noi them, false -> ghi de.
            fos = new FileOutputStream("vidu.txt", true);

            String str;
            do {
                System.out.println("Nhap chuoi can them vao File: ");
                str = "\n" + scan.nextLine();
                
                byte[] data = str.getBytes("utf8");

                fos.write(data);
            } while (!str.equalsIgnoreCase("N"));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    static void saveFile() {
        FileOutputStream fos = null;

        try {
            //true -> noi them, false -> ghi de.
            fos = new FileOutputStream("vidu.txt", true);

            String str = "\nSinh vien Aptech 123";
            byte[] data = str.getBytes("utf8");

            fos.write(data);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    static void testFile() {
        //Test File class
        File file = new File("test.txt");
        if (file.exists()) {
            System.out.println("path: " + file.getAbsolutePath());
        } else {
            System.out.println("File not exist");
            try {
                file.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        //List
        file = new File("./");
        File[] fileList = file.listFiles();
        int index = 1;
        for (File f : fileList) {
            if (f.isFile()) {
                System.out.println(index + ") " + f.getName());
            } else {
                System.out.println(index + ") " + f.getName() + " -> folder");
            }
            index++;
        }
    }
}


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)