Я пытаюсь читать и записывать записи из/в файл, и у меня есть некоторые проблемы. Файл создается, но он не записывается и, как результат, не читается. Я установил его, когда нажата кнопка, она должна писать и читать из файла и отображать содержимое в текстовое поле. Вот мой код:Чтение/запись в файлы 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");
}
}
Любая помощь будет оценена.
Спасибо!
Вы пробовали 'outfile.flush()' в конце 'writeToFile()'? – Turing85
Вы открываете свои файлы, но никого из них не закрываете. Более того, если вы используете Java 7+, используйте try-with-resources и java.nio.file. – fge
спасибо Turing85, что сработало. – user2101411