繁体   English   中英

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

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

我正在尝试这样做,以便每当用户输入名称并将其传递时,都会将该信息(以名称,传递的格式)写入到位置指定的.csv文件中。 但是,每当我运行该程序时,它都会覆盖第一行。 我尝试添加"\\n"out.newLine(); 但由于某种原因,它不会写入下一行。 我不知道为什么要这么做,所以我希望有人知道为什么。

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

}

当前在文件中我有这个:

测试,一个

当我运行程序时:

name: one
pass: two

退出程序并检查文件,第一行被替换为一,二,而不是像这样:

test, one
one, two

谢谢您的帮助:)

使用FileWriter的第二个构造函数:

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

fileName-字符串与系统有关的文件名。
append-布尔值(如果为true),则数据将被写入文件的末尾而不是开始。

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

暂无
暂无

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

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