如何搜索文本文件,填充二维数组然后搜索?

时间:2018-02-20 13:49:13

标签: java swing

简而言之,我的程序允许用户输入成员详细信息,然后将其写入新行的文本文件中。我在搜索时遇到问题。我要做的是当用户在文本字段中键入成员ID时,它会查看文本文件,如果该成员ID存在,则返回整行。

这是我的代码(我尝试了很多,但不知道在searchBtn下要做什么:

    /**
     * Creates new form Members
     */
    public Members() {
        initComponents();
    }

    String[][] membersArray = new String[3][5]; 
    String lineRead;
    int i = 0;
    int j;

    /**
     * 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")

    private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
        saveBtn.setEnabled(false);
        addBtn.setEnabled(true);

        try {
            FileWriter writer = new FileWriter("memberDetails.txt", true);
            writer.write(idTxt.getText() + "," + nameTxt.getText() + "," + addressTxt.getText() + "," + phoneTxt.getText() + "," + birthTxt.getText() + "\n");
            writer.close();
        }
        catch (IOException e){

        }
    }                                       

    private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {                                       
        saveBtn.setEnabled(true);
        addBtn.setEnabled(false);

        idTxt.setText("");
        nameTxt.setText("");
        addressTxt.setText("");
        phoneTxt.setText("");
        birthTxt.setText("");
    }                                      

    private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
        try {
            FileReader reader = new FileReader("memberDetails.txt");
            BufferedReader buffer = new BufferedReader(reader);

            while((lineRead = buffer.readLine()) !=null) {

                for (i = 0; i < 2; i ++) {
                    for (j = 0; j < 5; j++) {
                        membersArray[i][j] = String.valueOf(lineRead.split(","));
                    }
                }
            }

            if (searchTxt.getText() == membersArray[i][0]) {
                // Print whole line
            }

            reader.close();
            buffer.close();
        }
        catch (IOException e) {

        }
    }                                         

    /**
     * @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(Members.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Members.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Members.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Members.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 Members().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton addBtn;
    private javax.swing.JLabel addressLbl;
    private javax.swing.JTextField addressTxt;
    private javax.swing.JLabel birthLbl;
    private javax.swing.JTextField birthTxt;
    private javax.swing.JLabel idLbl;
    private javax.swing.JTextField idTxt;
    private javax.swing.JLabel nameLbl;
    private javax.swing.JTextField nameTxt;
    private javax.swing.JLabel phoneLbl;
    private javax.swing.JTextField phoneTxt;
    private javax.swing.JButton saveBtn;
    private javax.swing.JButton searchBtn;
    private javax.swing.JTextField searchTxt;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:0)

lineRead.split(",");返回一个数组,因此调用String.valueOf(lineRead.split(","));没有意义。

初始化一个大数组

String[][] membersArray = new String[20][5]; 

读取数据并复制到数组

int lineNumber = 0;
while((lineRead = buffer.readLine()) !=null) {
    // split line
    String [] parts = lineRead.split(",");
    // Save - but only if array is not full
    if (5 == parts.length && lineNumber < membersArray.length) {
        // Copy (could use System.arraycopy)
        membersArray[lineNumber][0] = parts[0];
        membersArray[lineNumber][1] = parts[1];
        membersArray[lineNumber][2] = parts[2];
        membersArray[lineNumber][3] = parts[3];
        membersArray[lineNumber][4] = parts[4];
        lineNumber += 1;

        // While we're here, check for match
        if (searchTxt.getText().equals(parts[0])) {
            // Fill in text boxes
            idTxt.setText(parts[0]);
            nameTxt.setText(parts[1]);
            addressTxt.setText(parts[2]);
            phoneTxt.setText(parts[3]);
            birthTxt.setText(parts[4]);
        }
    }
}