By GokiSoft.com| 20:59 06/05/2020|
Java Advanced

Share Code - Hướng dẫn dọc ghi dữ liệu trên File - C1907L

Share Code - Hướng dẫn dọc ghi dữ liệu trên File


- Tìm hiểu File, FileInputStream, FileOutStream, FileReader, FileWriter, BufferedRead, ObjectInputStream, ObjectOutputStream

#Source Code

##FileAndFileOutStream.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 lession3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class FileAndFileOutStream {
    public static void main(String[] args) {
        //Phan1 : File class
        File file = new File("vidu.txt");
        
        if(file.exists()) {
            System.out.println("File exist");
        } else {
            try {
                file.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(FileAndFileOutStream.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("File not found");
        }
        //Phan 2: Ghi du lieu vao file
        FileOutputStream fos = null;
        Scanner scan = new Scanner(System.in);
        
        try {
            fos = new FileOutputStream("test.txt", true);
            
//            String line = "TRAN VAN DIEP";
//            byte[] b = line.getBytes();
//            fos.write(b);
            for(;;) {
                System.out.println("Insert line into file: ");
                String line = scan.nextLine() + "\n";
                byte[] b = line.getBytes();
                
                fos.write(b);
                
                System.out.println("Continue Y/N: ");
                String choose = scan.nextLine();
                
                if(choose.equalsIgnoreCase("N")) {
                    break;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileAndFileOutStream.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileAndFileOutStream.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(FileAndFileOutStream.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }
}


##FileInputStreamTest.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 lession3;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class FileInputStreamTest {
    public static void main(String[] args) {
        FileInputStream fis = null;
        
        try {
            fis = new FileInputStream("test.txt");
            
//            int code = fis.read();
//            char c = (char) code;
//            System.out.println("c >> " + c);
            
            StringBuilder builder = new StringBuilder();
            int code;
            while((code = fis.read()) != -1) {
                builder.append((char) code);
            }
            
            String content = builder.toString();
            System.out.println(content);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileInputStreamTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileInputStreamTest.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(FileInputStreamTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        
    }
}


##FileReaderTest.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 lession3;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class FileReaderTest {
    public static void main(String[] args) {
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        
        try {
            reader = new FileReader("test.txt");
            bufferedReader = new BufferedReader(reader);
            
            String line;
            
            while((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileReaderTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileReaderTest.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(FileReaderTest.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            if(bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    Logger.getLogger(FileReaderTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


##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 lession3;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        
        studentList.add(new Student("A", "Ha Noi"));
        studentList.add(new Student("B", "Ha Nam"));
        studentList.add(new Student("C", "Nam Dinh"));
        
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream("student.txt");
            
            String line = Student.getFileHeaderFormat() + "\n";
            byte[] b = line.getBytes();

            fos.write(b);
            
            for (Student std : studentList) {
                line = std.getFileLineFormat() + "\n";
                b = line.getBytes();
                
                fos.write(b);
            }
        } 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);
                }
            }
        }
    }
}


##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 lession3;

import java.io.Serializable;

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

    public Student() {
    }

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

    public String getFullname() {
        return fullname;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    
    public String getFileLineFormat() {
        return fullname+","+address;
    }
    
    public static String getFileHeaderFormat() {
        return "fullname,address";
    }

    @Override
    public String toString() {
        return "Student{" + "fullname=" + fullname + ", address=" + address + '}';
    }
}


##Test.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 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;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class Test {
    public static void main(String[] args) {
//        saveFile();
        readFile();
    }
    
    static void readFile() {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        
        try {
            fis = new FileInputStream("student.dat");
            
            ois = new ObjectInputStream(fis);
            
//            List<Student> students = (List<Student>) ois.readObject();
//            
//            for (Student std : students) {
//                System.out.println(std);
//            }
            Object obj = null;
            while((obj = ois.readObject()) != null) {
                Student std = (Student) obj;
                System.out.println(std);
            }
        } 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(fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
    }
    
    static void saveFile() {
        List<Student> studentList = new ArrayList<>();
        
        studentList.add(new Student("A", "Ha Noi"));
        studentList.add(new Student("B", "Ha Nam"));
        studentList.add(new Student("C", "Nam Dinh"));
        
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        
        try {
            fos = new FileOutputStream("student.dat", true);
            oos = new ObjectOutputStream(fos);
            
//            oos.writeObject(studentList);
            for (Student student : studentList) {
                oos.writeObject(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);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


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

5

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