繁体   English   中英

读取/写入文件Java

[英]Reading/Writing to files Java

我正在尝试从文件读取条目或向文件写入条目,并且遇到一些问题。 正在创建文件,但未将其写入,因此无法读取。 我将其设置为单击按钮时,它应该写入文件并从文件中读取,并将内容显示到文本区域中。 这是我的代码:

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

任何帮助,将不胜感激。

谢谢!

尝试在writeToFile()的末尾添加

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

flush将告诉操作系统将文件写入媒体,而close将释放文件占用的资源。

BufferedReader会缓冲输入。 writeToFile() -方法的最后,您应该使用outfile.flush(); writeToFile() 将所有暂挂数据从缓冲区写入文件。 另外,完成后关闭资源: outfile.close(); 您可能想看看try-with-resources

暂无
暂无

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

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