我正在尝试从/向文件读取和写入条目,并且遇到了一些问题。正在创建文件,但它没有被写入,因此没有被读取。我将它设置为单击按钮时,它应该从文件中写入和读取并将内容显示到textarea中。这是我的代码:
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");
}
}
任何帮助将不胜感激。
谢谢!
答案 0 :(得分:1)
尝试在writeToFile()
的末尾添加outfile.flush();
outfile.close();
flush将告诉操作系统将文件写入媒体,关闭将释放文件占用的资源。
答案 1 :(得分:0)
BufferedReader
执行缓冲输入。在writeToFile()
- 方法的末尾,您应该使用outfile.flush();
将缓冲区中的所有待处理数据写入文件。此外,完成后请关闭资源:outfile.close();
。您可能需要查看try-with-resources