简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM