By GokiSoft.com| 15:07 07/04/2021|
Java Advanced

[Khoá học Java nâng cao] Chương trình quản lý thư viện + XML


- XML/JSON
- Java:
	- XML
		- save du lieu duoi format xml
		- doc du lieu tu xml ra chuong trinh phan mem nhu the nao?
================================================
Viết chương trình quản lý thư viện:
- Tác giả
	- nickname
	- fullname
	- email
	- address
	- birthday
- Sách
	- title
	- nickname
	- price
	- nxb
	- description
1. Nhập thông tin tác giả
2. Nhập thông tin sách
3. Hiển thị thông tin sách
4. Lưu thông tin vào file library.xml
5. Đọc nội dung library.xml
6. Kết thúc chương trình




#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 aptech.xml.lesson01;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    static List<Author> authors = new ArrayList<>();
    static List<Book> books = 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:
                    inputAuthor();
                    break;
                case 2:
                    inputBook();
                    break;
                case 3:
                    displayBook();
                    break;
                case 4:
                    saveFile();
                    break;
                case 5:
                    readFile();
                    break;
                case 6:
                    System.out.println("Goodbye!!!");
                    break;
                default:
                    System.out.println("Input failed!!!");
                    break;
            }
        } while(choose != 6);
    }
    
    static void showMenu() {
        System.out.println("1. Input author");
        System.out.println("2. Input book");
        System.out.println("3. Display book");
        System.out.println("4. Save library.xml");
        System.out.println("5. Read library.xml");
        System.out.println("6. Exit");
        System.out.println("Choose: ");
    }

    private static void inputAuthor() {
        System.out.println("Enter (N) author: ");
        int n = Integer.parseInt(scan.nextLine());
        
        for (int i = 0; i < n; i++) {
            Author author = new Author();
            author.input();
            
            authors.add(author);
        }
    }

    private static void inputBook() {
        System.out.println("Enter (N) book: ");
        int n = Integer.parseInt(scan.nextLine());
        
        for (int i = 0; i < n; i++) {
            Book book = new Book();
            book.input();
            
            books.add(book);
        }
    }

    private static void displayBook() {
        books.forEach((book) -> {
            System.out.println(book);
        });
    }

    private static void saveFile() {
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream("library.xml");
            
            String authorList = "";
            for (Author author : authors) {
                authorList += author.toXML();
            }
            
            String bookList = "";
            for (Book book : books) {
                bookList += book.toXML();
            }
            
            String content = toXML(authorList, bookList);
            
            byte[] data = content.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);
                }
            }
        }
    }
    
    private static String toXML(String authorList, String bookList) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "\n" +
                    "<library>\n" +
                    "	<author-list>\n" +
                    "\n" + authorList +
                    "	</author-list>\n" +
                    "	<book-list>\n" +
                    "		\n" + bookList + 
                    "	</book-list>\n" +
                    "</library>";
    }

    private static void readFile() {
        try {
            File file = new File("library.xml");
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            LibraryParser libraryParser = new LibraryParser();
            parser.parse(file, libraryParser);
            
            authors = libraryParser.authorList;
            books = libraryParser.bookList;
            
            displayBook();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


#LibraryParser.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 aptech.xml.lesson01;

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 Diep.Tran
 */
public class LibraryParser extends DefaultHandler{
    List<Author> authorList = new ArrayList<>();
    List<Book> bookList = new ArrayList<>();
    
    Author author = null;
    Book book = null;
    
    boolean isAuthor = false;
    boolean isNickname = false;
    boolean isFullname = false;
    boolean isEmail = false;
    boolean isAddress = false;
    boolean isBirthday = false;
    
    boolean isBook = false;
    boolean isTitle = false;
    boolean isNickname2 = false;
    boolean isPrice = false;
    boolean isNxb = false;
    boolean isDes = false;
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        //Doc xong open tag.
        if(qName.equalsIgnoreCase("author")) {
            isAuthor = true;
            author = new Author();
        }
        if(isAuthor) {
            if(qName.equalsIgnoreCase("nickname")) {
                isNickname = true;
            } else if(qName.equalsIgnoreCase("fullname")) {
                isFullname = true;
            } else if(qName.equalsIgnoreCase("email")) {
                isEmail = true;
            } else if(qName.equalsIgnoreCase("address")) {
                isAddress = true;
            } else if(qName.equalsIgnoreCase("birthday")) {
                isBirthday = true;
            }
        }
        
        if(qName.equalsIgnoreCase("book")) {
            isBook = true;
            book = new Book();
        }
        if(isBook) {
            if(qName.equalsIgnoreCase("title")) {
                isTitle = true;
            } else if(qName.equalsIgnoreCase("nickname")) {
                isNickname2 = true;
            } else if(qName.equalsIgnoreCase("price")) {
                isPrice = true;
            } else if(qName.equalsIgnoreCase("nxb")) {
                isNxb = true;
            } else if(qName.equalsIgnoreCase("description")) {
                isDes = true;
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        //Doc xong close tag.
        if(qName.equalsIgnoreCase("author")) {
            isAuthor = false;
            authorList.add(author);
            author = null;
        }
        if(isAuthor) {
            if(qName.equalsIgnoreCase("nickname")) {
                isNickname = false;
            } else if(qName.equalsIgnoreCase("fullname")) {
                isFullname = false;
            } else if(qName.equalsIgnoreCase("email")) {
                isEmail = false;
            } else if(qName.equalsIgnoreCase("address")) {
                isAddress = false;
            } else if(qName.equalsIgnoreCase("birthday")) {
                isBirthday = false;
            }
        }
        
        if(qName.equalsIgnoreCase("book")) {
            isBook = false;
            bookList.add(book);
            book = null;
        }
        if(isBook) {
            if(qName.equalsIgnoreCase("title")) {
                isTitle = false;
            } else if(qName.equalsIgnoreCase("nickname")) {
                isNickname2 = false;
            } else if(qName.equalsIgnoreCase("price")) {
                isPrice = false;
            } else if(qName.equalsIgnoreCase("nxb")) {
                isNxb = false;
            } else if(qName.equalsIgnoreCase("description")) {
                isDes = false;
            }
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        //Noi dung ben trong tag
        String str = String.valueOf(ch, start, length);
        if(isAuthor) {
            if(isNickname) {
                author.setNickname(str);
            } else if(isFullname) {
                author.setFullname(str);
            } else if(isEmail) {
                author.setEmail(str);
            } else if(isAddress) {
                author.setAddress(str);
            } else if(isBirthday) {
                author.setBirthday(str);
            }
        }
        
        if(isBook) {
            if(isTitle) {
                book.setTitle(str);
            } else if(isNickname2) {
                book.setNickname(str);
            } else if(isPrice) {
//                System.out.println("Price: " + str);
                book.setPrice(Float.parseFloat(str));
            } else if(isNxb) {
                book.setNxb(str);
            } else if(isDes) {
                book.setDescription(str);
            }
        }
    }
}


#Book.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 aptech.xml.lesson01;

import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Book {
    String title, nickname, nxb, description;
    float price;

    public Book() {
    }

    public Book(String title, String nickname, String nxb, String description, float price) {
        this.title = title;
        this.nickname = nickname;
        this.nxb = nxb;
        this.description = description;
        this.price = price;
    }

    public void input() {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Enter title: ");
        title = scan.nextLine();
        
        System.out.println("Enter nickname: ");
        nickname = scan.nextLine();
        
        System.out.println("Enter nha xuat ban: ");
        nxb = scan.nextLine();
        
        System.out.println("Enter description: ");
        description = scan.nextLine();
        
        System.out.println("Enter price: ");
        price = Float.parseFloat(scan.nextLine());
    }
    
    public String toXML() {
        return "		<book>\n" +
"			<title>"+title+"</title>\n" +
"			<nickname>"+nickname+"</nickname>\n" +
"			<price>"+price+"</price>\n" +
"			<nxb>"+nxb+"</nxb>\n" +
"			<description>"+description+"</description>\n" +
"		</book>\n";
    }
    
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getNxb() {
        return nxb;
    }

    public void setNxb(String nxb) {
        this.nxb = nxb;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" + "title=" + title + ", nickname=" + nickname + ", nxb=" + nxb + ", description=" + description + ", price=" + price + '}';
    }
}


#Author.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 aptech.xml.lesson01;

import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Author {
    String nickname, fullname, email, address, birthday;

    public Author() {
    }

    public Author(String nickname, String fullname, String email, String address, String birthday) {
        this.nickname = nickname;
        this.fullname = fullname;
        this.email = email;
        this.address = address;
        this.birthday = birthday;
    }
    
    public void input() {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Enter nickname: ");
        nickname = scan.nextLine();
        
        System.out.println("Enter fullname: ");
        fullname = scan.nextLine();
        
        System.out.println("Enter email: ");
        email = scan.nextLine();
        
        System.out.println("Enter address: ");
        address = scan.nextLine();
        
        System.out.println("Enter birthday (dd/mm/yyyy): ");
        birthday = scan.nextLine();
    }

    public String toXML() {
        return "		<author>\n" +
"			<nickname>"+nickname+"</nickname>\n" +
"			<fullname>"+fullname+"</fullname>\n" +
"			<email>"+email+"</email>\n" +
"			<address>"+address+"</address>\n" +
"			<birthday>"+birthday+"</birthday>\n" +
"		</author>\n";
    }
    
    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    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 String getAddress() {
        return address;
    }

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

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Author{" + "nickname=" + nickname + ", fullname=" + fullname + ", email=" + email + ", address=" + address + ", birthday=" + birthday + '}';
    }
}


Tags:

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

5

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