By GokiSoft.com| 15:31 12/07/2023|
Java Advanced

[Share Code] Tìm hiểu về File trong Java - C2209I

#Main.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.java2.lesson02;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 * @author teacher
 */
public class Main {
    static class DataController<E> {
        List<E> dataList;

        public DataController() {
            dataList = new ArrayList<>();
        }
        
        public void add(E e) {
            dataList.add(e);
        }
        
        public void show() {
            for (E e : dataList) {
                System.out.println(e);
            }
        }
    }
    
    static class People {
        String name;
        String cccd;

        public People(String name, String cccd) {
            this.name = name;
            this.cccd = cccd;
        }

        @Override
        public String toString() {
            return "name=" + name + ", cccd=" + cccd;
        }
    }
    
    static class Student extends People {
        String email;

        public Student(String email, String name, String cccd) {
            super(name, cccd);
            this.email = email;
        }
        
        @Override
        public String toString() {
            return super.toString() + ", email=" + email;
        }
    }
    
    static class PeopleController<E extends People> {
        List<E> dataList;

        public PeopleController() {
            dataList = new ArrayList<>();
        }
        
        public void add(E e) {
            dataList.add(e);
        }
        
        public void show() {
            for (E e : dataList) {
                System.out.println(e);
            }
        }
    }
    
    public static void main(String[] args) {
        //Mang quan ly danh sach so nguyen
        ArrayList<Integer> t1 = new ArrayList<>();
        
        t1.add(12);
        t1.add(343);
        
        //Mang String
        ArrayList<String> t2 = new ArrayList<>();
        t2.add("sdfsdf");
        t2.add("324234");
        
        
        HashMap<String, Integer> maps = new HashMap<>();
        maps.put("key1", 2342);
        
        DataController<String> controller = new DataController<>();
        controller.add("Vi du 1");
        controller.add("Vi du 2");
        controller.add("Vi du 3");
        controller.add("Vi du 4");
        controller.add("Vi du 5");
        
        controller.show();
        
//        PeopleController<String> peopleController = new PeopleController<>();
//        peopleController.add("Vi du 1");
//        peopleController.add("Vi du 2");
//        peopleController.add("Vi du 3");
//        
//        peopleController.show();

        PeopleController<Student> peopleController = new PeopleController<>();
        peopleController.add(new Student("A", "AA", "AAA"));
        peopleController.add(new Student("B", "AA", "AAA"));
        peopleController.add(new Student("C", "AA", "AAA"));
        
        peopleController.show();
    }
}

#Test.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.java2.lesson02;

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.Serializable;
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 teacher
 */
public class Test {
    static class Student implements Serializable{
        String name;
        String email;

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

        public String getName() {
            return name;
        }

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

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        @Override
        public String toString() {
            return "name=" + name + ", email=" + email;
        }
    }
    
    public static void main(String[] args) {
        //testFile();
        //saveFile01();
//        saveFile02();
//        readFile01();
//        readFile02();

//        saveFileObject();
        readFileObject();
    }
    
    static void readFileObject() {
        List<Student> dataList;
        
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            fis = new FileInputStream("student.dat");
            ois = new ObjectInputStream(fis);
            
            dataList = (List<Student>) ois.readObject();
            
            for (Student student : dataList) {
                System.out.println(student);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
    }
    
    static void saveFileObject() {
        List<Student> dataList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            dataList.add(new Student("Name " + i, "email: " + i));
        }
        
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        
        try {
            fos = new FileOutputStream("student.dat");
            oos = new ObjectOutputStream(fos);
            
            oos.writeObject(dataList);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(oos != null) {
                try {
                    oos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    static void readFile02() {
        //Doc noi dung tieng viet co dau
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        
        try {
            reader = new FileReader("data02.txt");
            bufferedReader = new BufferedReader(reader);
            String line;
            
            while((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    static void readFile01() {
        //Doc toan bo noi dung -> Hien thi ra man hinh
        //Su dung doc File -> ASCII (256)
        StringBuilder builder = new StringBuilder();
        
        FileInputStream fis = null;
        
        try {
            fis = new FileInputStream("data02.txt");
            
            int code;
            while((code = fis.read()) != -1) {
                builder.append((char) code);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        System.out.println(builder.toString());
    }
    
    static void saveFile02() {
        Scanner scan = new Scanner(System.in);
        
        //Doc du lieu tu keyboard -> Luu vao file
        FileOutputStream fos = null;
        
        try {
            //Mo ket noi toi File - mo ghi override noi dung
//            fos = new FileOutputStream("data01.txt");
            //Mo ket noi toi File - mo ghi override noi dung
            fos = new FileOutputStream("data02.txt", true);
            
            //Luu noi dung thong tin vao File
            do {
                System.out.println("Nhap noi dung can ghi vao File: \n");
                String s = scan.nextLine();
                if(s.equalsIgnoreCase("N") || s.isEmpty()) {
                    break;
                }
                byte[] b = ("\n"+s).getBytes("utf8");
                fos.write(b);
            } while(true);
//            System.out.println("Nhap noi dung can ghi vao File: \n");
//            String s = scan.nextLine();
//            byte[] b = s.getBytes("utf8");
//            fos.write(b);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    //Dong ket noi
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    static void saveFile01() {
        //Luu 1 String vao trong file
        String s = "\nSINH VIEN APTECH 19 LE THANH NGHI - C2209I - 3";
        
        FileOutputStream fos = null;
        
        try {
            //Mo ket noi toi File - mo ghi override noi dung
//            fos = new FileOutputStream("data01.txt");
            //Mo ket noi toi File - mo ghi override noi dung
            fos = new FileOutputStream("data01.txt", true);
            
            //Luu noi dung thong tin vao File
            byte[] b = s.getBytes("utf8");
            fos.write(b);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    //Dong ket noi
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    static void testFile() {
        File file = new File("vidu.txt");
        
        if(file.exists()) {
            System.out.println("File vidu.txt exists");
        } else {
            System.out.println("File vidu.txt not exists");
            try {
                file.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
Tags:



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

5

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

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó