如何在Java中使用表格和.txt?

How to use tables and .txt in Java?

我正在构建一个汽车租赁程序,目前我想要的是:

使用 .txt 文件存储数据。

使用我编写的代码,我只能注册一个汽车和一个用户。每次我运行客户或汽车的注册方法,最后一个注册被擦除。

你能帮我解决这个问题吗?还有,后面我要实现一个租车的方法,但是我也不知道怎么做,所以如果你有什么想法,请告诉我!

我也打算不做 SQL 之类的东西。

这是我用来注册用户的代码(我使用的是带有 JForm 的 netbeans):

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String nomeClient = txtNomeClient.getText();
    String idClient = txtIdClient.getText();

    File file = new File("clients.txt");

    try {
        PrintWriter output = new PrintWriter(file);
        output.println(nomeClient);
        output.println(idClient);
        output.close();
        JOptionPane.showMessageDialog(null, "Client registed!");
    } catch (FileNotFoundException e) {
    }

}

问题是您覆盖现有文件clients.txt,而不是通过调用[=13]附加到它=].您可以使用以下代码:

FileWriter fileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(fileWriter));

通过这种方式,您可以追加到文件末尾,请参阅构造函数 FileWriter(File file, boolean append)。文档完美地描述了它:

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

FileWriter 仅用于以附加模式打开文件,因为 PrintWriter 没有合适的构造函数来直接执行此操作。你也可以用它写字符,但是 PrintWriter 允许格式化输出。来自FileWriterdocumentation

Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.

PrintWriter 使用在其构造函数中传递的 FileWriter 附加到目标文件,请参阅 here 以获得很好的解释。如此处所述,您还可以使用 FileOutputStream。有多种方法可以做到这一点。

这是一个使用 FileOutputStreamBufferedWriter 的示例,它支持缓冲并可以减少不必要的写入,从而降低性能。

FileOutputStream fileOutputStream = new FileOutputStream("clients.txt", true); 
BufferedWriter bufferedWriter = new BufferedWriter(fileOutputStream);
PrintWriter printWriter = new PrintWriter(bufferedWriter);