By GokiSoft.com|
16:13 15/03/2021|
Java Advanced
[Share Code] Tìm hiểu ObjectInputStream + ObjectOutputStream - Thread - Lập trình Java
#Test2.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 bt1071;
/**
*
* @author Diep.Tran
*/
public class Test2 {
static Thread t1, t2 = null;
public static void main(String[] args) {
//Main Thread -> luong chinh
System.out.println("Step 1");
t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Step 2 - " + i);
if(i == 5) {
t2.start();
}
}
}
});
t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Step 3 - " + i);
// t1.stop();
}
}
});
// t2.start();//T2 -> chay => T2 & Main
t1.start();//T1 -> chay => T1 & Main & T2
System.out.println("Finish");
}
}
#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 bt1071;
import aptech.java2.lession3.FileInOutStream;
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) {
// writeData();
readData();
}
static void readData() {
List<Student> studentList = new ArrayList<>();
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("student.dat");
ois = new ObjectInputStream(fis);
// studentList = (List<Student>) ois.readObject();
while(true) {
Object obj = ois.readObject();
if(obj != null) {
studentList.add((Student) obj);
} else {
break;
}
}
} 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 {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
try {
ois.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
for (Student student : studentList) {
student.display();
}
}
static void writeData() {
List<Student> studentList = new ArrayList<>();
Student std1 = new Student();
std1.input();
studentList.add(std1);
Student std2 = new Student();
std2.input();
studentList.add(std2);
//Luu du lieu vao FILE.
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("student.dat");
oos = new ObjectOutputStream(fos);
//Lam viec voi List
// oos.writeObject(studentList);
//Lam viec voi Object
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 {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
try {
oos.close();
} catch (IOException ex) {
Logger.getLogger(Test.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 bt1071;
import java.io.Serializable;
import java.util.Scanner;
/**
*
* @author Diep.Tran
*/
public class Student implements Serializable{
//id: tu tang -> giai phap la gi?
static int count = 0;
int id = 0, age;
String name, address;
float gpa;
public Student() {
id = ++count;
}
public Student(int age, String name, String address, float gpa) {
this.age = age;
this.name = name;
this.address = address;
this.gpa = gpa;
id = ++count;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
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;
}
public float getGpa() {
return gpa;
}
public void setGpa(float gpa) {
this.gpa = gpa;
}
public void input() {
Scanner abc = new Scanner(System.in);
// System.out.println("Nhap ID: ");
// id = Integer.parseInt(abc.nextLine());
System.out.println("Nhap ten: ");
name = abc.nextLine();
System.out.println("Nhap dia chi: ");
address = abc.nextLine();
System.out.println("Nhap tuoi: ");
age = Integer.parseInt(abc.nextLine());
System.out.println("Nhap GPA: ");
gpa = Float.parseFloat(abc.nextLine());
}
public String getFileLine() {
return id + "," + name + "," + age + "," + address + "," + gpa + "\n";
}
public void parse(String line) {
String[] params = line.split(",");
try {
id = Integer.parseInt(params[0]);
name = params[1];
age = Integer.parseInt(params[2]);
address = params[3];
gpa = Float.parseFloat(params[4]);
} catch(ArrayIndexOutOfBoundsException ex) {
} finally {
}
}
public void display() {
System.out.println(this);
}
@Override
public String toString() {
return "Student{" + "id=" + id + ", age=" + age + ", name=" + name + ", address=" + address + ", gpa=" + gpa + '}';
}
}
#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 bt1071;
import aptech.java2.lession3.FileInOutStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Diep.Tran
*/
public class Main {
static List<Student> studentList = new ArrayList<>();
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int choose;
do {
showMenu();
choose = Integer.parseInt(scan.nextLine());
switch(choose) {
case 1:
inputStudent();
break;
case 2:
editStudentById();
break;
case 3:
deleteStudentById();
break;
case 4:
sortStudentByGPA();
break;
case 5:
sortStudentByName();
break;
case 6:
displayStudent();
break;
case 7:
saveFile();
break;
case 8:
readFile();
break;
case 9:
System.out.println("Thoat!!!");
break;
default:
System.out.println("Nhap sai!!!");
break;
}
} while(choose != 9);
}
static void showMenu() {
System.out.println("1. Them sinh vien");
System.out.println("2. Sua sinh vien theo id");
System.out.println("3. Xoa sinh vien theo id");
System.out.println("4. Sap xep theo GPA");
System.out.println("5. Sap xep theo ten");
System.out.println("6. Hien thi thong tin sinh vien");
System.out.println("7. Luu vao file student.txt");
System.out.println("8. Doc noi dung sinh vien tu student.txt");
System.out.println("9. Thoat");
System.out.println("Chon: ");
}
private static void inputStudent() {
System.out.println("Nhap so sinh vien can them: ");
int n = Integer.parseInt(scan.nextLine());
for (int i = 0; i < n; i++) {
Student std = new Student();
std.input();
studentList.add(std);
}
}
private static void editStudentById() {
System.out.println("Nhap id sinh vien can sua: ");
int id = Integer.parseInt(scan.nextLine());
for (Student student : studentList) {
if(student.getId() == id) {
student.input();
break;
}
}
}
private static void deleteStudentById() {
System.out.println("Nhap id sinh vien can xoa: ");
int id = Integer.parseInt(scan.nextLine());
for (Student student : studentList) {
if(student.getId() == id) {
studentList.remove(student);
break;
}
}
}
private static void sortStudentByGPA() {
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if(o1.getGpa() > o2.getGpa()) {
return -1;
}
return 1;
}
});
}
private static void sortStudentByName() {
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
//Z-A (A-Z: them dau - truoc)
}
});
}
private static void displayStudent() {
for (Student student : studentList) {
student.display();
}
}
private static void saveFile() {
//Luu file
System.out.println("Bat dau luu:");
FileOutputStream fos = null;
try {
fos = new FileOutputStream("student.txt", true);
//luu du lieu
for (Student student : studentList) {
String line = student.getFileLine();
//chuyen string to byte[]
byte[] b = line.getBytes("utf8");
//Save
fos.write(b);
}
} 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);
}
}
}
}
private static void readFile() {
FileInputStream fis = null;
InputStreamReader reader = null;
BufferedReader bufferedReader = null;
try {
fis = new FileInputStream("student.txt");
reader = new InputStreamReader(fis, StandardCharsets.UTF_8);
bufferedReader = new BufferedReader(reader);
String line = null;
while((line = bufferedReader.readLine()) != null) {
if(line.isEmpty()) {
continue;
}
Student std = new Student();
std.parse(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(fis != null) {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
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);
}
}
}
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)