Sc4r
Sc4r

Reputation: 700

Writing to a new line in a .csv file without overwriting the first line

I'm trying to make it so whenever a user inputs a name and pass it will write that information(in the format of name,pass) to a .csv file specified by the location. However whenever I run the program, it keeps overwriting the first line. I tried adding "\n" and out.newLine(); but for some reason it doesn't write to the next line. I have no idea why it does this so I was hoping if someone knows why.

public class TestClass {

    public static void main(String[] args) throws IOException {

        String location = "my location to the file (.csv)";

        Scanner sc = new Scanner(System.in);
        System.out.print("Name: ");
        String name = sc.next();
        System.out.print("Pass: ");
        String pass = sc.next();
        BufferedWriter out = new BufferedWriter(new FileWriter(location));
        out.write(name + "," + pass + "\n");
        out.newLine();
        out.close();
    }

}

Currently in the file I have this:

test, one

and when I ran the program:

name: one
pass: two

exited the program and checked the file and the first line was replaced with one,two instead of making it like this:

test, one
one, two

Thank you for those who help :)

Upvotes: 1

Views: 4119

Answers (1)

Eng.Fouad
Eng.Fouad

Reputation: 117587

Use the second constructor of FileWriter:

FileWriter(String fileName, boolean append)

fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.

BufferedWriter out = new BufferedWriter(new FileWriter(location, true));

Upvotes: 3

Related Questions