简体   繁体   English

写入.csv文件中的新行而不会覆盖第一行

[英]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. 我正在尝试这样做,以便每当用户输入名称并将其传递时,都会将该信息(以名称,传递的格式)写入到位置指定的.csv文件中。 However whenever I run the program, it keeps overwriting the first line. 但是,每当我运行该程序时,它都会覆盖第一行。 I tried adding "\\n" and out.newLine(); 我尝试添加"\\n"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的第二个构造函数:

FileWriter(String fileName, boolean append) FileWriter(字符串fileName,布尔值附加)

fileName - String The system-dependent filename. fileName-字符串与系统有关的文件名。
append - boolean if true, then data will be written to the end of the file rather than the beginning. append-布尔值(如果为true),则数据将被写入文件的末尾而不是开始。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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