By GokiSoft.com|
20:11 05/08/2022|
Java Advanced
[Source Code] Tìm hiểu XML & JSON trong Java - C2108L
#students.json
[
{
"rollno": "R001",
"fullname": "Tran Van A",
"email": "a@gmail.com"
},
{
"rollno": "R002",
"fullname": "Tran Van B",
"email": "a@gmail.com"
},
{
"rollno": "R003",
"fullname": "Tran Van C",
"email": "a@gmail.com"
},
{
"rollno": "R004",
"fullname": "Tran Van D",
"email": "a@gmail.com"
},
{
"rollno": "R005",
"fullname": "Tran Van E",
"email": "a@gmail.com"
},
{
"rollno": "AAA",
"fullname": "AAA",
"email": "AAA"
},
{
"rollno": "BBB",
"fullname": "BBB",
"email": "BBB"
}
]
#students.xml
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student>
<rollno>R001</rollno>
<fullname>Tran Van A</fullname>
<email>a@gmail.com</email>
</student>
<student>
<rollno>R002</rollno>
<fullname>Tran Van B</fullname>
<email>a@gmail.com</email>
</student>
<student>
<rollno>R003</rollno>
<fullname>Tran Van C</fullname>
<email>a@gmail.com</email>
</student>
<student>
<rollno>R004</rollno>
<fullname>Tran Van D</fullname>
<email>a@gmail.com</email>
</student>
<student>
<rollno>R005</rollno>
<fullname>Tran Van E</fullname>
<email>a@gmail.com</email>
</student>
<student>
<rollno>AAA</rollno>
<fullname>AAA</fullname>
<email>AAA</email>
</student>
<student>
<rollno>BBB</rollno>
<fullname>BBB</fullname>
<email>BBB</email>
</student>
</students>
#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 lesson09;
import java.util.Scanner;
/**
*
* @author QTA
*/
public class Student {
String rollno;
String fullname;
String email;
public Student() {
}
public Student(String rollno, String fullname, String email) {
this.rollno = rollno;
this.fullname = fullname;
this.email = email;
}
public String getRollno() {
return rollno;
}
public void setRollno(String rollno) {
this.rollno = rollno;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void input() {
Scanner scan = new Scanner(System.in);
System.out.println("Nhap msv: ");
rollno = scan.nextLine();
System.out.println("Nhap ten: ");
fullname = scan.nextLine();
System.out.println("Nhap email: ");
email = scan.nextLine();
}
@Override
public String toString() {
return "Student{" + "rollno=" + rollno + ", fullname=" + fullname + ", email=" + email + '}';
}
public void display() {
System.out.println(this);
}
public String toXML() {
return "<student>\n" +
" <rollno>"+rollno+"</rollno>\n" +
" <fullname>"+fullname+"</fullname>\n" +
" <email>"+email+"</email>\n" +
" </student>";
}
}
#StudentHandler.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 lesson09;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author QTA
*/
public class StudentHandler extends DefaultHandler{
List<Student> studentList = null;
Student std = null;
boolean isRollno = false;
boolean isFullname = false;
boolean isEmail = false;
public StudentHandler() {
studentList = new ArrayList<>();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attr) throws SAXException {
if(qName.equalsIgnoreCase("student")) {
std = new Student();
} else if(qName.equalsIgnoreCase("rollno")) {
isRollno = true;
} else if(qName.equalsIgnoreCase("fullname")) {
isFullname = true;
} else if(qName.equalsIgnoreCase("email")) {
isEmail = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("student")) {
studentList.add(std);
std = null;
} else if(qName.equalsIgnoreCase("rollno")) {
isRollno = false;
} else if(qName.equalsIgnoreCase("fullname")) {
isFullname = false;
} else if(qName.equalsIgnoreCase("email")) {
isEmail = false;
}
}
@Override
public void characters(char[] chars, int start, int length) throws SAXException {
String value = new String(chars, start, length);
if(isRollno) {
std.setRollno(value);
} else if(isFullname) {
std.setFullname(value);
} else if(isEmail) {
std.setEmail(value);
}
}
public List<Student> getStudentList() {
return studentList;
}
public void setStudentList(List<Student> studentList) {
this.studentList = studentList;
}
}
#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 lesson09;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import static lesson09.Test2.readText;
import org.xml.sax.SAXException;
/**
*
* @author QTA
*/
public class Test {
static List<Student> studentList = null;
static InputStreamReader reader = null;
static BufferedReader bReader = null;
public static void main(String[] args) throws IOException {
studentList = new ArrayList<>();
int choose;
reader = new InputStreamReader(System.in);
bReader = new BufferedReader(reader);
do {
showMenu();
choose = Integer.parseInt(bReader.readLine());
switch(choose) {
case 1:
inputStudent();
break;
case 2:
displayStudent();
break;
case 3:
readXML();
break;
case 4:
saveXML();
break;
case 5:
readJSON();
break;
case 6:
saveJSON();
break;
case 7:
System.out.println("Exit!!!");
break;
default:
System.out.println("Input failed!!!");
break;
}
} while(choose != 7);
}
static void showMenu() {
System.out.println("1. Input Student");
System.out.println("2. Display Student");
System.out.println("3. Read XML");
System.out.println("4. Save XML");
System.out.println("5. Read JSON");
System.out.println("6. Save JSON");
System.out.println("7. Exit");
System.out.println("Choose: ");
}
static void readXML() {
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
StudentHandler handler = new StudentHandler();
parser.parse(new File("students.xml"), handler);
studentList = handler.getStudentList();
for (Student student : studentList) {
student.display();
}
} catch (ParserConfigurationException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void inputStudent() {
System.out.println("Nhap so sinh vien can them: ");
int n = 0;
try {
n = Integer.parseInt(bReader.readLine());
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
for (int i = 0; i < n; i++) {
Student std = new Student();
std.input();
studentList.add(std);
}
}
private static void displayStudent() {
System.out.println("Danh sach sinh vien: ");
for (Student student : studentList) {
student.display();
}
}
private static void saveXML() {
String xml = toXML();
saveFile(xml, "students.xml");
}
static String toXML() {
StringBuilder builder = new StringBuilder();
for (Student student : studentList) {
builder.append(student.toXML());
}
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"\n" +
"<students>\n" +
builder.toString() +
"</students>";
}
private static void readJSON() {
Gson gson = new Gson();
String content = readText("students.json");
Type type = new TypeToken<List<Student>>(){}.getType();
studentList = gson.fromJson(content, type);
for (Student student : studentList) {
student.display();
}
}
private static void saveJSON() {
//Convert studentList -> JSON String
Gson gson = new Gson();
Type type = new TypeToken<List<Student>>(){}.getType();
String json = gson.toJson(studentList, type);
//save json -> file
saveFile(json, "students.json");
}
static void saveFile(String content, String filename) {
FileWriter writer = null;
BufferedWriter bWriter = null;
try {
writer = new FileWriter(filename);
bWriter = new BufferedWriter(writer);
bWriter.write(content);
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(bWriter != null) {
try {
bWriter.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(writer != null) {
try {
writer.close();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static String readText(String filename) {
FileReader reader = null;
BufferedReader bReader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new FileReader(filename);
bReader = new BufferedReader(reader);
String line;
while((line = bReader.readLine()) != null) {
builder.append(line);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(bReader != null) {
try {
bReader.close();
} catch (IOException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(reader != null) {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return builder.toString();
}
}
#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 lesson09;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author QTA
*/
public class Test2 {
public static void main(String[] args) {
readJSON();
}
static void readJSON() {
List<Student> studentList = null;
Gson gson = new Gson();
String content = readText("students.json");
Type type = new TypeToken<List<Student>>(){}.getType();
studentList = gson.fromJson(content, type);
for (Student student : studentList) {
student.display();
}
}
static String readText(String filename) {
FileReader reader = null;
BufferedReader bReader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new FileReader(filename);
bReader = new BufferedReader(reader);
String line;
while((line = bReader.readLine()) != null) {
builder.append(line);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(bReader != null) {
try {
bReader.close();
} catch (IOException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(reader != null) {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(Test2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return builder.toString();
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)