java java中如何读写txt文件中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25600758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:18:45  来源:igfitidea点击:

How to write and read data in txt file in java

javaswingio

提问by Umar Farooq

I am new to SO, I have designed a form in java, I added three buttons Submit, Clearand Show Record. I need to get data on submit event and pass it to txt file, and i want to show whole record on show record button click event. I need quick fix by you people, I am running out of time. Here is my Code:

我是 SO 新手,我用 java 设计了一个表单,我添加了三个按钮SubmitClearShow Record。我需要获取有关提交事件的数据并将其传递给 txt 文件,并且我想在显示记录按钮单击事件中显示整个记录。我需要你们快速修复,我的时间不多了。这是我的代码:

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;
        }
    }   
}

回答by Paul Samsotha

First let me point out some faulty (but not deadly) design. All your checkXxx()methods handle the obtaining of the text from the fields. I would change them to accept Strings as arguments. The reason is that you are going to need those String values from the text fields in the scope of the actionPerformed, in order to save them to your text file.

首先让我指出一些错误的(但不是致命的)设计。您所有的checkXxx()方法都处理从字段中获取文本。我会将它们更改为接受字符串作为参数。原因是您将需要 范围内文本字段中的那些字符串值actionPerformed,以便将它们保存到您的文本文件中。

I need to get data on submit event and pass it to txt file

我需要获取有关提交事件的数据并将其传递给 txt 文件

You should use a FileWriterand use this constructor

您应该使用 aFileWriter并使用此构造函数

public FileWriter(String fileName, boolean append) throws IOException-
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

public FileWriter(String fileName, boolean append) throws IOException-
构造一个 FileWriter 对象,给定一个带有布尔值的文件名,指示是否附加写入的数据。

that will allow you to append to the file with one of its appendmethods.

这将允许您使用其中一种append方法附加到文件中。

and i want to show whole record on show record button click event

我想在显示记录按钮单击事件上显示整个记录

Not sure if you mean you want to read allthe records or read a single record based of a name or something. For the former, text components have a read()method to read an entire document onto the text component (say a text area). For the latter, you are going to need to read line by line and check if some part of the line matches the data you want to match. This is basic io stuff. You can read more at Basic I/O. For example, something like (assuming your records/lines are comma separated values):

不确定您的意思是要读取所有记录还是基于名称或其他内容读取单个记录。对于前者,文本组件具有read()将整个文档读取到文本组件(例如文本区域)上的方法。对于后者,您将需要逐行读取并检查该行的某些部分是否与您想要匹配的数据相匹配。这是基本的io东西。您可以在基本 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();

The above code just reads line by line, splitting each line into an array. It checks the first token to see if a name matches a field value. If it does, then you can use the values form the array to populate the fields.

上面的代码只是逐行读取,将每一行拆分成一个数组。它检查第一个标记以查看名称是否与字段值匹配。如果是,那么您可以使用数组中的值来填充字段。

If you wanted to read the whole file onto a text area, you could simple pass the same BufferedReaderto the readmethod like textArea.read(reader, null);

如果您想将整个文件读取到文本区域,您可以简单地将相同的内容传递BufferedReaderread方法,例如textArea.read(reader, null);

回答by lasa

Before I provide an answer corrected some of the codes you have mistakenly done.

在我提供答案之前,纠正了您错误地完成的一些代码。

Please check the area where I corrected.

请检查我更正的区域。

Your code:

您的代码:

    // 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

Modified Code:

修改后的代码:

    // 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

============================ Then I defined new two methods for read file and for write to file

============================ 然后我定义了两个新的读取文件和写入文件的方法

This is Writing to file

这是写入文件

      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);
                }
                ///
}

This is read File

这是读取文件

private void 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);
}
}

Then added new if statement in side the actionPerforemed(ActionEvent e) to handle the event from "Show Records" Button where you have not added it. in side it I call the readFile() which will print the all line from reading file.(This reading file is same file where you going to write.)

然后在 actionPerforemed(ActionEvent e) 旁边添加新的 if 语句来处理来自“显示记录”按钮的事件,您尚未添加它。在它旁边,我调用 readFile() 它将打印读取文件中的所有行。(此读取文件与您要写入的文件相同。)

         //Newly added event for Show Records button. 

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

Then in side the actionPerforemed(ActionEvent e) and in the if statement related to submit button

然后在 actionPerforemed(ActionEvent e) 和与提交按钮相关的 if 语句中

Added Following Code.

添加了以下代码。

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) {
    }
}