【问题标题】:Writing to a new line in a .csv file without overwriting the first line写入 .csv 文件中的新行而不覆盖第一行
【发布时间】:2014-12-28 07:42:28
【问题描述】:

我正在努力做到这一点,因此每当用户输入名称并传递它时,它将将该信息(以名称,传递的格式)写入该位置指定的 .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

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

test, one
one, two

感谢帮助的人:)

【问题讨论】:

    标签: java file io java-io filewriter


    【解决方案1】:

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

    FileWriter(String fileName, boolean append)

    fileName - String 系统相关的文件名。
    append - 布尔值,如果为真,那么数据将被写入文件的末尾而不是开头.

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

    【讨论】:

    • 谢谢 Eng Fouad :)。不知道真实的部分:O.
    • @Sc4r 欢迎您。阅读 JavaDocs 总是一个好主意 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2021-11-11
    • 2014-02-05
    • 1970-01-01
    相关资源
    最近更新 更多