簡體   English   中英

如何在Java中的txt文件中寫入和讀取數據

[英]How to write and read data in txt file in java

我是SO的新手,我在Java中設計了一個表單,添加了三個按鈕SubmitClearShow Record 我需要獲取有關Submit事件的數據並將其傳遞到txt文件,並且我想在show record button click事件中顯示整個記錄。 我需要您快速修復,我已經沒時間了。 這是我的代碼:

import java.awt.*;  //import older gui library for content pane
import javax.swing.*;   //import newer gui library for labels, textfields, and button
import java.awt.event.*; //import gui event action library
import javax.swing.JRadioButton;

public class CustomerRecord extends JFrame implements ActionListener {

    // declare labels used on GUI screen
    private JLabel labelId, labelName, labelGender,labelcategory, labelPItem, labeldiscount;
    private JLabel labelError, labelRegistration; 
    private JTextField textId, textName, textGender, textState, textcategory, textPItem, textdiscount;
    // declare button used on GUI screen
    private JButton submitButton, clearButton, readButton;
    final JRadioButton jRadioMale = new JRadioButton("Male");
    final JRadioButton jRadioFemale = new JRadioButton("Female");
    // declare content pane
    private Container contentPane;

    public CustomerRecord() {
        createGUI();
    } // ends  constructor

    private void createGUI() {
        try {
            // get content pane and set the layout to null
            contentPane = getContentPane();
            contentPane.setLayout(null);    //free-form layout
            setFont(new Font("TimesRoman", Font.ITALIC, 14));

            // create the name label
            labelId = new JLabel(); //instantiate new JLabel
            labelId.setText("C.ID");    //set label text to name
            labelId.setLocation(38, 10);    //set location of JLabel
            labelId.setSize(200, 25);   //set size of JLabel
            labelId.setForeground(Color.BLACK);//set initial background color
            contentPane.add(labelId);   //add JLabel to content pane

            // create the name text box
            textName = new JTextField();    //instantiate new JTextField
            textName.setText("");   //clear JTextField
            textName.setToolTipText("Please enter ID");
            textName.setLocation(75, 10);   //set location of JTextFfield
            textName.setSize(200, 25);   //set size of JTextField
            contentPane.add(textName); //add jextfield to content pane

            // create the address label
            labelName = new JLabel();
            labelName.setText("Name:");
            labelName.setLocation(23, 50);
            labelName.setSize(80, 25);
            labelName.setForeground(Color.BLACK);
            contentPane.add(labelName);

            // create the address text box
            textName = new JTextField();
            textName.setText("");
            textName.setToolTipText("Please type in full name");
            textName.setLocation(75, 50);
            textName.setSize(300, 25);
            contentPane.add(textName);
            labelGender = new JLabel();
            labelGender.setText("Gender");
            labelGender.setLocation(30, 90);
            labelGender.setSize(300, 25);
            labelGender.setForeground(Color.BLACK);
            contentPane.add(labelGender);
            textGender = new JTextField();
            textGender.setText("");
            textGender.setToolTipText("M/F");
            textGender.setLocation(75, 90);
            textGender.setSize(130, 25);
            contentPane.add(textGender);
            labelcategory = new JLabel();
            labelcategory.setText("Category");
            labelcategory.setLocation(18, 170);
            labelcategory.setSize(300, 25);
            labelcategory.setForeground(Color.BLACK);
            contentPane.add(labelcategory);
            textcategory = new JTextField();
            textcategory.setText("");
            textcategory.setToolTipText("Item Type (Grocery)");
            textcategory.setLocation(75, 170);
            textcategory.setSize(130, 25);
            contentPane.add(textcategory);
            labelPItem = new JLabel();
            labelPItem.setText("Total Item");
            labelPItem.setLocation(15, 210);
            labelPItem.setSize(250, 25);
            labelPItem.setForeground(Color.BLACK);
            contentPane.add(labelPItem);
            textPItem = new JTextField();
            textPItem.setText("");
            textPItem.setToolTipText("Purchased items must be between start with 1 or 70");
            textPItem.setLocation(75, 210);
            textPItem.setSize(130, 25);
            contentPane.add(textPItem);
            labeldiscount = new JLabel();
            labeldiscount.setText("Discount");
            labeldiscount.setLocation(18, 250);
            labeldiscount.setSize(300, 25);
            labeldiscount.setForeground(Color.BLACK);
            contentPane.add(labeldiscount);
            textdiscount = new JTextField();
            textdiscount.setText("");
            textdiscount.setToolTipText("Entered Value must be containing ' % '");
            textdiscount.setLocation(75, 250);
            textdiscount.setSize(130, 25);
            contentPane.add(textdiscount);
            submitButton = new JButton();
            submitButton.setText("Submit");
            submitButton.setToolTipText("Click \"submit \" when the form is completely filled out");
            submitButton.setLocation(125, 450);
            submitButton.setSize(100, 30);
            contentPane.add(submitButton);
            submitButton.addActionListener(this);
            readButton = new JButton();
            readButton.setText("Show Records");
            readButton.setToolTipText("Click Show Record if you want to check record");
            readButton.setLocation(225, 350);
            readButton.setSize(200, 30);
            contentPane.add(readButton);
            readButton.addActionListener(this);

            clearButton = new JButton();
            clearButton.setText("Clear");
            clearButton.setToolTipText("Click \"clear \" when you want to clear the form");
            clearButton.setLocation(250, 450);
            clearButton.setSize(100, 30);
            contentPane.add(clearButton);
            clearButton.addActionListener(this);

            // create the error label
            labelError = new JLabel();
            labelError.setText("Please correct items in red");
            labelError.setLocation(150, 500);
            labelError.setSize(190, 25);
            labelError.setForeground(Color.RED);
            labelError.setVisible(false);
            contentPane.add(labelError);

            // create the registration label
            labelRegistration = new JLabel();
            labelRegistration.setText("Thank you for your entry.");
            labelRegistration.setLocation(145, 500);
            labelRegistration.setSize(190, 25);
            labelRegistration.setForeground(Color.BLACK);
            labelRegistration.setVisible(false);
            contentPane.add(labelRegistration);

            setTitle("Customer Form");  //set window title
            setSize(475, 600); //set window size
            setVisible(true);
        } catch (Exception e) {
        }
    }// ends creatGUI method.

    public static void main(String args[]) {
        CustomerRecord application = new CustomerRecord();
        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }// ends main

    public void actionPerformed(ActionEvent event) {
        try {
            if (event.getActionCommand().equals("Submit")) {

                if (checkID() & checkName() & checkGender() &  check() & checkPItem() & checkdiscount()) {
                    labelRegistration.setVisible(true);
                    labelError.setVisible(false);    
                    submitButton.removeActionListener(this); 
                    clearButton.removeActionListener(this);  
                } else {
                    labelError.setVisible(true); 
                    labelRegistration.setVisible(false); 
                }
            } if (event.getActionCommand().equals("Clear")) 
                {
                textName.setText("");
                textName.setText("");
                textGender.setText("");
                textState.setText("");
                textcategory.setText("");
                textPItem.setText("");
                textdiscount.setText("");

                labelError.setVisible(false);
                labelRegistration.setVisible(false);
                labelId.setForeground(Color.BLACK);
                labelName.setForeground(Color.BLACK);
                labelGender.setForeground(Color.BLACK);
                labelcategory.setForeground(Color.BLACK);
                labelPItem.setForeground(Color.BLACK);
                labeldiscount.setForeground(Color.BLACK);

            }
        } catch (Exception e) { }
    }
    private boolean checkID() {
        if (textName.getText().length() == 0) {
            labelId.setForeground(Color.RED);   //name is not correct
            return false;
        } else {
            labelId.setForeground(Color.BLACK); //name is correct
            return true;
        }
    } 
    private boolean checkName() {
        if (textName.getText().length() < 5) {
            labelName.setForeground(Color.RED); 
            return false;
        } else {
            labelName.setForeground(Color.BLACK);
            return true;
        }
    } 

    private boolean checkGender() {
        if (textGender.getText().length() == 0) {
            labelGender.setForeground(Color.RED);
            return false;
        } else {
            labelGender.setForeground(Color.BLACK); 
            return true;
        }
    } 
    private boolean check() {
        try {

            if (textcategory.getText().length() == 5) {
                labelcategory.setForeground(Color.BLACK);
                return true;
            } else {
                labelcategory.setForeground(Color.RED); 
                return false;
            }
        } catch (Exception e) {
            labelcategory.setForeground(Color.RED);     
            return false;
        }
    } 
    private boolean checkPItem() {

            if (textPItem.getText().startsWith("1") || textPItem.getText().startsWith("70")) 
            {
                labelPItem.setForeground(Color.BLACK);
                return true;
            } else {
                labelPItem.setForeground(Color.RED);    
                return false;
            }      
    } 
    private boolean checkdiscount() {
        if (textdiscount.getText().contains("%"))
        {
            labeldiscount.setForeground(Color.BLACK);
                return true;
        } else
        {
            labeldiscount.setForeground(Color.RED); 
                return false;
        }
    }   
}

首先讓我指出一些錯誤的(但不是致命的)設計。 您的所有checkXxx()方法都處理從字段中獲取文本的問題。 我將其更改為接受字符串作為參數。 原因是您將需要來自actionPerformed范圍內的文本字段中的那些String值,以便將它們保存到文本文件中。

我需要獲取有關提交事件的數據並將其傳遞給txt文件

您應該使用FileWriter並使用此構造函數

public FileWriter(String fileName, boolean append) throws IOException
構造一個給定文件名的FileWriter對象,該文件名帶有一個布爾值,該布爾值指示是否追加寫入的數據。

這將允許您使用其append方法之一將其append到文件。

我想在顯示記錄按鈕單擊事件中顯示整個記錄

不知道您是要讀取所有記錄還是要讀取基於名稱或其他內容的單個記錄。 對於前者,文本組件具有read()方法,可將整個文檔讀取到文本組件(例如文本區域)上。 對於后者,您將需要逐行讀取並檢查行的某些部分是否與您要匹配的數據匹配。 這是基本的io東西。 您可以在Basic I / O上閱讀更多內容。 例如,類似(假設您的記錄/行是逗號分隔的值):

BufferedReader reader = new Bufferedreader(new FileReader(new File("file")));
String line = null;
while ((line = reader.readLine()) != null) {
    String[] tokens = line.split(",");
    String firstName = tokens[0].trim();
    if (firstName.equals(firstNameFieldtext)) {
        // use the tokens to populate the fields.
        break;
    }
}
reader.close();

上面的代碼僅逐行讀取,將每一行拆分為一個數組。 它檢查第一個標記以查看名稱是否與字段值匹配。 如果是這樣,則可以使用數組中的值填充字段。

如果您想將整個文件讀取到文本區域,則可以簡單地將相同的BufferedReader傳遞給read方法,例如textArea.read(reader, null);

在我提供答案之前,請更正您錯誤執行的一些代碼。

請檢查我更正的區域。

您的代碼:

    // create the name text box
        textName = new JTextField();    //instantiate new JTextField
        textName.setText("");   //clear JTextField
        textName.setToolTipText("Please enter ID");
        textName.setLocation(75, 10);   //set location of JTextFfield
        textName.setSize(200, 25);   //set size of JTextField
        contentPane.add(textName); //add jextfield to content pane

修改后的代碼:

    // create the name text box
        textId = new JTextField();    //instantiate new JTextField
        textId.setText("");   //clear JTextField
        textId.setToolTipText("Please enter ID");
        textId.setLocation(75, 10);   //set location of JTextFfield
        textId.setSize(200, 25);   //set size of JTextField
        contentPane.add(textId); //add jextfield to content pane

然后,我定義了兩個新方法來讀取文件和寫入文件

這是寫入文件

      private void writeToFile(String list) throws IOException{
///
                File f = new File("E:\\test1.txt");
                System.out.println(f);
                FileWriter fw = new FileWriter(f,true);
                System.out.println(fw);
                try{
                    BufferedWriter bw = new BufferedWriter(fw);
                    System.out.println(bw);
                    bw.newLine();
                    bw.write(list);
                    bw.flush();
                    bw.close();
                }
                catch(Exception e){
                    System.out.println(e);
                }
                ///
}

這是讀取文件

私有無效readFile(){

     File f = new File("E:\\test1.txt");
try{
       FileReader fr = new FileReader(f);
       BufferedReader br = new BufferedReader(fr);
       while(br.ready()){
       System.out.println(br.readLine());
        }
}catch(Exception e){
    System.out.println(e);
}
}

然后在actionPerforemed(ActionEvent e)旁邊添加新的if語句,以處理尚未添加事件的“顯示記錄”按鈕中的事件。 從側面講,我調用readFile(),它將打印讀取文件的所有行。(此讀取文件與您要寫入的文件相同。)

         //Newly added event for Show Records button. 

        if (event.getActionCommand().equals("Show Records")) {
           readFile();
        }

然后在旁邊的actionPerforemed(ActionEvent e)和與提交按鈕有關的if語句中

添加了以下代碼。

public void actionPerformed(ActionEvent event) {
    try {
        if (event.getActionCommand().equals("Submit")) {

            if (checkID() & checkName() & checkGender() & check() & checkPItem() & checkdiscount()) {
                labelRegistration.setVisible(true);
                labelError.setVisible(false);
                //concatnating the collected data to be written.
                String toBewrite = textId.getText() + "," + textName.getText();
                toBewrite = toBewrite + "," + textGender.getText() + "," + textcategory.getText();
                toBewrite = toBewrite + "," + textPItem.getText() + "," + textdiscount.getText();
                ///calling the writeToFile method where the relavent data to be updated to the file.
                writeToFile(toBewrite);
                ////
                submitButton.removeActionListener(this);
                clearButton.removeActionListener(this);
            } else {
                labelError.setVisible(true);
                labelRegistration.setVisible(false);
            }
        }
        if (event.getActionCommand().equals("Clear")) {
            textName.setText("");
            textName.setText("");
            textGender.setText("");
            textState.setText("");
            textcategory.setText("");
            textPItem.setText("");
            textdiscount.setText("");

            labelError.setVisible(false);
            labelRegistration.setVisible(false);
            labelId.setForeground(Color.BLACK);
            labelName.setForeground(Color.BLACK);
            labelGender.setForeground(Color.BLACK);
            labelcategory.setForeground(Color.BLACK);
            labelPItem.setForeground(Color.BLACK);
            labeldiscount.setForeground(Color.BLACK);

        }
        //Newly added event for Show Records button.
        if (event.getActionCommand().equals("Show Records")) {
            readFile();
        }
    } catch (Exception e) {
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM