Ressay
Ressay

Reputation: 69

Adding data to CSV file using java

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.

Upvotes: 1

Views: 4433

Answers (3)

HarryQ
HarryQ

Reputation: 1433

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());
    }

Upvotes: 2

Joop Eggen
Joop Eggen

Reputation: 109623

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());
    }
}

Upvotes: 0

Vladimir Pligin
Vladimir Pligin

Reputation: 1660

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);

Upvotes: 4

Related Questions