-1

Im building a Car Rental program and what I want it to, for now, is:

  • Register a user
  • Register a car

using .txt files to store the data.

With the code I've written, I can register only a single car and user. Every time I run the register method for client or car, the last register is erased.

Can you help me with this? Also, later I'm going to implement a way to rent a car, but I don't know how to do that also, so if you have any ideas of how to do it, please tell me!

Also I intend to do it without SQL or such things.

This is the code I'm using to register a user (I'm using netbeans with JForm):

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) {
    }

}

1 Answers1

2

The problem is that you overwrite the existing file clients.txt, instead of appending to it by calling new PrintWriter(file). You can use the following code:

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

This way, you append the end of the file, see the constructor FileWriter(File file, boolean append). The documentation describes it perfectly:

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.

The FileWriter is just used to open a file in append mode, as PrintWriter does not have a suitable constructor to do that directly. You could also write characters with it, but a PrintWriter allows for formatted output. From the documentation of FileWriter:

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.

The PrintWriter uses the FileWriter passed in its constructor to append to the destination file, see here for a good explanation. As stated there, you could also use an FileOutputStream. There are multiple ways to do this.

Here is an example using a FileOutputStream and a BufferedWriter, which supports buffering and can reduce unnecessary writes that penalize performance.

FileOutputStream fileOutputStream = new FileOutputStream("clients.txt", true); 
BufferedWriter bufferedWriter = new BufferedWriter(fileOutputStream);
PrintWriter printWriter = new PrintWriter(bufferedWriter);
Community
  • 1
  • 1
thatguy
  • 21,059
  • 6
  • 30
  • 40