简体   繁体   English

Java文件不会在所有行的末尾保存新行

[英]Java file doesn't save new lines in the end of all lines

I've a problem with saving data to csv file. 将数据保存到csv文件时出现问题。 When I want save data, it saves it sth like this: 当我想保存数据时,它会像这样保存数据:

new data
2017-02-12
new

But I'd like it save sth like this in the end of the file: 但我希望它在文件末尾保存以下内容:

new data,2017-02-12,new

My code: 我的代码:

public static void writeData(String filepath, List<String> lines) {

    Path file = Paths.get(filepath);
    try {
        Files.write(file, lines, StandardOpenOption.APPEND);
    } catch (IOException e) {
        System.out.println("Something went wrong with saving data to file!");
    }
}

Thanks in advance! 提前致谢!

Files.write(Path, Iterable<? extends CharSequence>, OpenOption...) is writing to file line by line. Files.write(Path, Iterable<? extends CharSequence>, OpenOption...)正在Files.write(Path, Iterable<? extends CharSequence>, OpenOption...)写入文件。 If your list contains items "new data", "2017-02-12", "new" then each item will be printed on separate line. 如果您的列表中包含“新数据”,“ 2017-02-12”,“新”项目,则每个项目将打印在单独的行上。

If you want to print them together at single line you have to concatenate them before adding to your list. 如果要将它们一起打印在一行上,则必须先将它们串联起来,然后再添加到列表中。

String[] columns = new String[] {"new data", "2017-02-12", "new"};
String row = String.join(",", columns);
List<String> rows = new LinkedList<>();
rows.add(row);

// calling your method to save lines
writeData("data.csv", rows);

I guess you are using the wrong function to write the data to your file. 我猜您使用的是错误的函数,将数据写入文件中。 To quote the Java API for the function Files::write you are using: 引用函数File :: write的Java API,您正在使用:

"Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. " ( source ) “每行都是一个char序列,并按顺序写入文件,每行由平台的行分隔符终止,这由系统属性line.separator定义。”(

The "line separator" is something like "\\n", "\\n\\r", "\\r" (depending on your file system). “行分隔符”类似于“ \\ n”,“ \\ n \\ r”,“ \\ r”(取决于文件系统)。

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

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