IMG-LOGO
×

Tài Liệu Học

Khoá học lập trình Java Core nâng cao

Exception & Collection

[Video] Tìm hiểu exception + debug + package - lập trình Java Nâng Cao [Video] Tìm hiểu collections, Sets, Maps và Generic - lập trình java nâng cao [Video] Chương trình quản lý sinh viên bằng HashMap - Java Advanced

File

[Video] Hướng dẫn đọc ghi file FileInputStream, FileOutputStream, ObjectInputStream trong java - lập trình java nâng cao [Video] Bài tập quản lý sách & lưu thông tin trên Files [Video] File - Quản lý thông tin sinh viên [Video] Quản lý thông tin sinh & lưu object file - Java nâng cao [Video] Viết ứng dụng WinRar | WinZip | 7Zip bằng Java - Nén file Java & giải nén file Java - Khoá học Java [Video] Bài tập quản lý bán vé máy bay - java nâng cao

Thread

[Video] Phân tích quản lý ứng dụng trong HĐH (Window, Mac, Linux)-Phân tích Game đa luồng Java [Video] Tìm hiểu Thread - Đồng bộ Thread - lập trình java nâng cao - Bổ sung thêm lớp học mới. [Video] Giải thích synchronized + Lap trinh Java nang cao [Video] Thread thực hiện in ngẫu nhiên các số nguyên và ký tự - Phần 1 [Video] Thread thực hiện in ngẫu nhiên các số nguyên và ký tự & Đông bộ thread + wait notify + synchronized + Java nâng cao - Phần 2 [Video] Synchronized 2 Thread - Bài tập mảng tên + địa chỉ - Java nâng cao [Video] Bài tập ôn luyện tổng hợp File, OOP, Thread trong java [Video] Sử dụng MultiThreading sinh ký tự a-zA-Z trong java

CSDL

[Video] Kết nối MySQL trong java swing JDBC trong java - lập trình java nâng cao [Video] Kết nối CSDL bằng java swing phần 1 - lập trình java nâng cao [Video] Kết nối CSDL bằng java swing phần 2 - lập trình java nâng cao [Video] Chương trình quản lý thư viện Java + XML Java + CSDL Java- SQL Java [Video] Phần mềm quản lý sinh viên MySQL + Java - Chương trình quản lý sinh viên MySQL + Java - Lập Trình Java [Video] Bài Tập Quản Lý Sinh Viên - CSDL - Java Swing [Video] Chương trình quản lý sản phẩm - quản lý tin tức - quản lý bán hàng - Lập trình Java [Video] Chức năng register & login + CSDL - Lập trình Java nâng cao - Phần 1 [Video] Hướng dẫn sử dụng Persistence Java - Kết nối database Java - MySQL Java nâng cao

Design Pattern & Đa Ngôn Ngữ

[Video] Design Pattern lập trình java nâng cao - lập trình java nâng cao

XML & JSON & CSDL

[Video] C1 > Chương trình quản lý sinh viên Java + Import/Export JSON + File - Lập Trình Java [Video] C2 > Chương trình quản lý sinh viên Java + Import/Export JSON + File - Lập Trình Java

Ôn Tập Tổng Quát & Exmination

[Video] Bài tập - Chường trình quản lý sở thú - Lập trình Java - Lập trình Java nâng cao - Phần 1 [Video] Bài tập - Chường trình quản lý sở thú - Lập trình Java - Lập trình Java nâng cao - Phần 2




Trang Chủ Java Advanced Bài tập - Viết chương trình quản lý sinh viên XML - JSON - Lập trình Java

Bài tập - Viết chương trình quản lý sinh viên XML - JSON - Lập trình Java

by GokiSoft.com - 08:55 22/09/2021 1,362 Lượt Xem

Yêu cầu thiết kế giao diện sau:

Tạo 1 file json đặt tên là db.json lưu danh sách sinh viên -> gồm các trường theo form trên.

Khi người dùng nhập -> mã sinh viên -> Click vào search button -> Hiển thị thông tin sinh viên ra Form.

Khi click vào update: Nếu sinh viên tồn tai thì update, nếu chưa tồn tại thì thêm mới sinh viên và lưu vào file db.json

Khi click vào export thì xuất thông tin sinh viên ra file student.xml

Bình luận



Phản Hồi Bởi:

(1) GokiSoft.com [Teacher]

Chia sẻ từ lớp học

GokiSoft.com [Teacher]

Ngày viết: 10:38 22/09/2021


#db.json


[{"fullname":"A","rollno":"R001","email":"[email protected]","address":"Ha Noi","gender":"Nam"},{"fullname":"BB","rollno":"R002","email":"[email protected]","address":"Nam Dinh","gender":"Nam"},{"fullname":"C","rollno":"R003","email":"[email protected]","address":"Ha Noi","gender":"Nam"},{"fullname":"AA","rollno":"R005","email":"[email protected]","address":"Ha Noi","gender":"Nam"},{"fullname":"AA","rollno":"R004","email":"[email protected]","address":"Ha Noi","gender":"Nam"},{"fullname":"C","rollno":"R006","email":"[email protected]","address":"Ha Noi","gender":"Nam"},{"fullname":"C","rollno":"R007","email":"[email protected]","address":"Ha Noi","gender":"Nam"}]


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

/**
 *
 * @author Diep.Tran
 */
public class Student {
    String fullname, rollno, email, address, gender;

    public Student() {
    }

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

    public String getFullname() {
        return fullname;
    }

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

    public String getRollno() {
        return rollno;
    }

    public void setRollno(String rollno) {
        this.rollno = rollno;
    }

    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 getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}


#StudentFrame.form


<?xml version="1.0" encoding="UTF-8" ?>

<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
  <Properties>
    <Property name="defaultCloseOperation" type="int" value="3"/>
    <Property name="title" type="java.lang.String" value="QUAN LY SINH VIEN"/>
  </Properties>
  <SyntheticProperties>
    <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
    <SyntheticProperty name="generateCenter" type="boolean" value="false"/>
  </SyntheticProperties>
  <AuxValues>
    <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
    <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
    <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
  </AuxValues>

  <Layout>
    <DimensionLayout dim="0">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" alignment="0" attributes="0">
              <EmptySpace min="-2" pref="33" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="0" attributes="0">
                  <Group type="102" attributes="0">
                      <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
                      <EmptySpace min="-2" pref="48" max="-2" attributes="0"/>
                      <Component id="fullnameTxt" min="-2" pref="240" max="-2" attributes="0"/>
                      <EmptySpace type="separate" max="-2" attributes="0"/>
                      <Component id="searchBtn" min="-2" pref="100" max="-2" attributes="0"/>
                  </Group>
                  <Group type="103" alignment="0" groupAlignment="1" max="-2" attributes="0">
                      <Group type="102" attributes="0">
                          <Component id="jLabel4" min="-2" max="-2" attributes="0"/>
                          <EmptySpace max="32767" attributes="0"/>
                          <Component id="emailTxt" min="-2" pref="240" max="-2" attributes="0"/>
                      </Group>
                      <Group type="102" attributes="0">
                          <Component id="jLabel3" min="-2" max="-2" attributes="0"/>
                          <EmptySpace max="32767" attributes="0"/>
                          <Component id="rollnoTxt" min="-2" pref="240" max="-2" attributes="0"/>
                      </Group>
                      <Group type="102" attributes="0">
                          <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
                          <EmptySpace min="-2" pref="48" max="-2" attributes="0"/>
                          <Component id="genderTxt" min="-2" pref="240" max="-2" attributes="0"/>
                      </Group>
                      <Group type="102" alignment="1" attributes="0">
                          <Component id="jLabel5" min="-2" max="-2" attributes="0"/>
                          <EmptySpace max="32767" attributes="0"/>
                          <Group type="103" groupAlignment="0" attributes="0">
                              <Group type="102" attributes="0">
                                  <Component id="saveBtn" min="-2" max="-2" attributes="0"/>
                                  <EmptySpace max="-2" attributes="0"/>
                                  <Component id="resetBtn" min="-2" max="-2" attributes="0"/>
                              </Group>
                              <Component id="addressTxt" min="-2" pref="240" max="-2" attributes="0"/>
                          </Group>
                      </Group>
                  </Group>
              </Group>
              <EmptySpace pref="15" max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
    <DimensionLayout dim="1">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" alignment="0" attributes="0">
              <EmptySpace min="-2" pref="26" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="fullnameTxt" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="searchBtn" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace type="separate" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="genderTxt" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace type="separate" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="rollnoTxt" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace type="separate" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jLabel4" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="emailTxt" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace type="separate" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="jLabel5" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="addressTxt" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace type="separate" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="3" attributes="0">
                  <Component id="saveBtn" alignment="3" min="-2" max="-2" attributes="0"/>
                  <Component id="resetBtn" alignment="3" min="-2" max="-2" attributes="0"/>
              </Group>
              <EmptySpace pref="14" max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Component class="javax.swing.JLabel" name="jLabel1">
      <Properties>
        <Property name="text" type="java.lang.String" value="Ho &amp; Ten:"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JTextField" name="fullnameTxt">
    </Component>
    <Component class="javax.swing.JTextField" name="genderTxt">
    </Component>
    <Component class="javax.swing.JLabel" name="jLabel2">
      <Properties>
        <Property name="text" type="java.lang.String" value="Gioi Tinh:"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JTextField" name="rollnoTxt">
    </Component>
    <Component class="javax.swing.JLabel" name="jLabel3">
      <Properties>
        <Property name="text" type="java.lang.String" value="Roll No:"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JTextField" name="emailTxt">
    </Component>
    <Component class="javax.swing.JLabel" name="jLabel4">
      <Properties>
        <Property name="text" type="java.lang.String" value="Email:"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JTextField" name="addressTxt">
    </Component>
    <Component class="javax.swing.JLabel" name="jLabel5">
      <Properties>
        <Property name="text" type="java.lang.String" value="Dia Chi:"/>
      </Properties>
    </Component>
    <Component class="javax.swing.JButton" name="saveBtn">
      <Properties>
        <Property name="text" type="java.lang.String" value="Luu"/>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="saveBtnActionPerformed"/>
      </Events>
    </Component>
    <Component class="javax.swing.JButton" name="resetBtn">
      <Properties>
        <Property name="text" type="java.lang.String" value="Xoa"/>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="resetBtnActionPerformed"/>
      </Events>
    </Component>
    <Component class="javax.swing.JButton" name="searchBtn">
      <Properties>
        <Property name="text" type="java.lang.String" value="Tim Kiem"/>
      </Properties>
      <Events>
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="searchBtnActionPerformed"/>
      </Events>
    </Component>
  </SubComponents>
</Form>


#StudentFrame.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 xml.bt2418;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;

/**
 *
 * @author Diep.Tran
 */
public class StudentFrame extends javax.swing.JFrame {
    List<Student> studentList;
    /**
     * Creates new form StudentFrame
     */
    public StudentFrame() {
        initComponents();
        
        String json = Utility.getContentFromFile("./src/xml/bt2418/db.json");
        
        Gson gson = new Gson();
        studentList = gson.fromJson(json, new TypeToken<List<Student>>(){}.getType());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        fullnameTxt = new javax.swing.JTextField();
        genderTxt = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        rollnoTxt = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        emailTxt = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        addressTxt = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        saveBtn = new javax.swing.JButton();
        resetBtn = new javax.swing.JButton();
        searchBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("QUAN LY SINH VIEN");

        jLabel1.setText("Ho & Ten:");

        jLabel2.setText("Gioi Tinh:");

        jLabel3.setText("Roll No:");

        jLabel4.setText("Email:");

        jLabel5.setText("Dia Chi:");

        saveBtn.setText("Luu");
        saveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveBtnActionPerformed(evt);
            }
        });

        resetBtn.setText("Xoa");
        resetBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetBtnActionPerformed(evt);
            }
        });

        searchBtn.setText("Tim Kiem");
        searchBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(48, 48, 48)
                        .addComponent(fullnameTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(searchBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(emailTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(rollnoTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addGap(48, 48, 48)
                            .addComponent(genderTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel5)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(saveBtn)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(resetBtn))
                                .addComponent(addressTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(fullnameTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchBtn))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(genderTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(rollnoTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(emailTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(addressTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveBtn)
                    .addComponent(resetBtn))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchBtnActionPerformed
        // TODO add your handling code here:
        String rollno = rollnoTxt.getText().trim();
        for (Student student : studentList) {
            if(student.getRollno().equalsIgnoreCase(rollno)) {
                fullnameTxt.setText(student.getFullname());
                genderTxt.setText(student.getGender());
                addressTxt.setText(student.getAddress());
                emailTxt.setText(student.getEmail());
                rollnoTxt.setText(student.getRollno());
                return;
            }
        }
    }//GEN-LAST:event_searchBtnActionPerformed

    private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
        // TODO add your handling code here:
        String rollno = rollnoTxt.getText().trim();
        for (Student student : studentList) {
            if(student.getRollno().equalsIgnoreCase(rollno)) {
                student.setFullname(fullnameTxt.getText());
                student.setGender(genderTxt.getText());
                student.setAddress(addressTxt.getText());
                student.setEmail(emailTxt.getText());
                
                saveFile();
                return;
            }
        }
        
        Student std = new Student(
                fullnameTxt.getText(), 
                rollnoTxt.getText(), 
                emailTxt.getText(), 
                addressTxt.getText(), 
                genderTxt.getText()
        );
        studentList.add(std);
        saveFile();
    }//GEN-LAST:event_saveBtnActionPerformed

    private void saveFile() {
        Gson gson = new Gson();
        String content = gson.toJson(studentList);
        Utility.saveFile(content, "./src/xml/bt2418/db.json");
    }
    
    private void resetBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetBtnActionPerformed
        // TODO add your handling code here:
        fullnameTxt.setText("");
        genderTxt.setText("");
        addressTxt.setText("");
        emailTxt.setText("");
        rollnoTxt.setText("");
    }//GEN-LAST:event_resetBtnActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new StudentFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField addressTxt;
    private javax.swing.JTextField emailTxt;
    private javax.swing.JTextField fullnameTxt;
    private javax.swing.JTextField genderTxt;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JButton resetBtn;
    private javax.swing.JTextField rollnoTxt;
    private javax.swing.JButton saveBtn;
    private javax.swing.JButton searchBtn;
    // End of variables declaration//GEN-END:variables
}


#Utility.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 xml.bt2418;

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

/**
 *
 * @author Diep.Tran
 */
public class Utility {
    public static String getContentFromFile(String filename) {
        StringBuilder builder = new StringBuilder();
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        
        try {
            reader = new FileReader(filename);
            bufferedReader = new BufferedReader(reader);
            
            String line;
            while((line = bufferedReader.readLine()) != null) {
                builder.append(line);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        return builder.toString();
    }
    
    public static void saveFile(String content, String filename) {
        FileOutputStream fos = null;
        
        try {
            fos = new FileOutputStream(filename);
            
            byte[] data = content.getBytes("utf8");
            
            fos.write(data);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


Phân Loại Bài Viết

Tài Liệu Tham Khảo

Đã sao chép!!!