1

I posted an earlier question asking about how to write to a CSV file, and I got lots of support but unfortunately every time the code runs it overwrites the old data, but I need to add to the data of the file not to overwrite it.

the application is a simple login page that stores the username and password injected by the user inside a CSV file.

 public void setCreateButton() throws Exception {

    String newUsername = usernameTextField.getText();
    String newUserPassword = passwordField.getText();
    String confirmedPassword = confirmPasswordField.getText();

    try {
        if (newUserPassword.equals(confirmedPassword)) {
            File file = new File("D:\\Users\\login.csv");
            PrintWriter printWriter = new PrintWriter(file);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(newUsername);
            stringBuilder.append(',');
            stringBuilder.append(newUserPassword);
            stringBuilder.append('\n');
            printWriter.write(stringBuilder.toString());
            printWriter.flush();
            printWriter.close();
        } else {
            System.out.println("Password are not matched");
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

Every time the button is clicked, it overwrites the data in the CSV file, I just need something to skip any line that is existing in the file and add a new line with the new data.

Renato
  • 2,077
  • 1
  • 11
  • 22
Ressay
  • 69
  • 9
  • 1
    Hi! These lines: File file = new File("D:\\Users\\login.csv"); PrintWriter printWriter = new PrintWriter(file); Means that you always create a new file each time the button is pressed. I'd suggest you do a check first if there is an existing file. If there isn't, then create a new one. If there is, just load it and append to it. Start with getting the logic/check right first. Then I can help you with appending to if you can't figure that out – GamingFelix Feb 07 '20 at 15:09
  • 1
    unrelated to fx .. – kleopatra Feb 07 '20 at 15:36
  • [How do you append to a text file instead of overwriting it in Java?](https://stackoverflow.com/questions/4269302/how-do-you-append-to-a-text-file-instead-of-overwriting-it-in-java) – Abra Feb 07 '20 at 16:48

3 Answers3

4

The easiest way to achieve the desired behavior here is to use FileWriter. It has a constructor that takes a boolean argument, you should pass true to it in order to have your file being appended not overwritten. Something like that:

FileWriter fr = new FileWriter(file, true);
PrintWriter printWriter = new PrintWriter(fr);
Vladimir Pligin
  • 1,547
  • 11
  • 18
2

If you don't want to deal with all sorts of writers, printers (those names are confusing to me at least), you can use the Files.write() function. It handles the file opening and closing for you and it is in the core java library.

Your code could be

 try {
        if (newUserPassword.equals(confirmedPassword)) {
            Path filePath = Paths.get("./file.csv");
            if (Files.notExists(filePath)) {
                filePath.toFile().createNewFile();
            }

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(newUsername);
            stringBuilder.append(',');
            stringBuilder.append(newUserPassword);
            stringBuilder.append(System.lineSeparator());

            Files.write(filePath, stringBuilder.toString().getBytes(), StandardOpenOption.APPEND);
        } else {
            System.out.println("Password are not matched");
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
HarryQ
  • 1,281
  • 2
  • 10
  • 25
  • A nice easy way, I really liked it, but still, it overwrites the file every time I press the button – Ressay Feb 08 '20 at 00:26
  • 1
    @Ressay I tested the code, it did the append in my program, did you set the APPEND options in the write function? Also you need to test if the file existence so you will only create the file once. – HarryQ Feb 08 '20 at 01:47
0

Use the APPEND mode of BufferedWriter. And better use full Unicode support, that is, store the log file in UTF-8. Especially for passwords you do not want to see ?s from locally unconvertable Unicode symbols.

FileWriter should not be used, though it can append, as it writes in the default platform encoding.

public void setCreateButton() throws Exception {
    String newUsername = usernameTextField.getText();
    String newUserPassword = passwordField.getText();
    String confirmedPassword = confirmPasswordField.getText();
    try {
        if (newUserPassword.equals(confirmedPassword)) {
            Path file = Paths.get("D:\\Users\\login-utf8.csv");
            try (PrintWriter printWriter =
                   new PrintWriter(Files.newBufferedWriter(file, StandardCharsets.UTF_8,
                       StandardOpenOptions.CREATE, StandardOpenOptions.APPEND)) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(newUsername);
                stringBuilder.append(',');
                stringBuilder.append(newUserPassword);
                stringBuilder.append('\n');
                printWriter.write(stringBuilder.toString());
            }
        } else {
            System.out.println("Password are not matched");
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138