简体   繁体   English

读取/写入文件Java

[英]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() 尝试在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. flush将告诉操作系统将文件写入媒体,而close将释放文件占用的资源。

The BufferedReader does buffer input. BufferedReader会缓冲输入。 At the end of you writeToFile() - method, you should use outfile.flush(); writeToFile() -方法的最后,您应该使用outfile.flush(); writeToFile() to write all pending data from the buffer to the file. 将所有暂挂数据从缓冲区写入文件。 Also, close your resources, when you are done: outfile.close(); 另外,完成后关闭资源: outfile.close(); . You may want to take a look at the try-with-resources 您可能想看看try-with-resources

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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