简体   繁体   中英

Reading/Writing to files Java

I am trying to read and write entries from/to a file and am having some issues. The file is being created, but it is not being written to and as a result not being read. I have it set to when the button is clicked, it should write and read from a file and display the contents into a textarea. Here is my code:

public void actionPerformed(ActionEvent event) 
{
    if (event.getSource() == this.saveToFile) {
        // save to file
       try {
           if (Integer.parseInt(this.age.getText()) > 0 && Integer.parseInt(this.age.getText()) <= 120) {
               this.openFile();
               this.writeToFile();
           } else {
               JOptionPane.showMessageDialog(rootPane, "Age must be greater than zero and no more than 120");
           }
       } catch (IOException e) {
           // ignore
       }
    } else if (event.getSource() == this.exitProgram) {
        System.exit(0);
    } else if (event.getSource() == this.readFromFile) {
        // read from file
        this.openFile();
        this.readFile();
    }
}

private void openFile()
{
    try {
        this.scan = new Scanner(new File("contacts.txt"));
    } catch (Exception e) {
        // ignore
    }
}

private void writeToFile() throws IOException
{
     BufferedWriter outfile = new BufferedWriter(new FileWriter("contacts.txt"));

     outfile.write("Name: ");
     outfile.write(this.name.getText());

     outfile.write("Age: ");
     outfile.write(this.age.getText());

     outfile.write("Email: ");
     outfile.write(this.email.getText());

     outfile.write("Cell Phone: ");
     outfile.write(this.cell.getText());

     outfile.write("\n\n");
}

private void readFile()
{
    while (this.scan.hasNext()) {
        this.textArea.append(this.scan.next() + "\t");
    }
}

Any help would be appreciated.

Thanks!

Try to add at the end of writeToFile()

outfile.flush();
outfile.close();

flush will tell the os to write the file to the media and close will free resources taken by the file.

The BufferedReader does buffer input. At the end of you writeToFile() - method, you should use outfile.flush(); to write all pending data from the buffer to the file. Also, close your resources, when you are done: outfile.close(); . You may want to take a look at the try-with-resources

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM