java将列表字符串写入csv文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35749250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:05:43  来源:igfitidea点击:

java write the list string into csv file

javaarrayscsvwriter

提问by mOna

I have some array strings like the following (note that there is space after each player which shows different lines...),

我有一些如下所示的数组字符串(请注意,每个播放器后面都有空格显示不同的行......),

["user1","track1","player1", "user1","track2","player2", "user1","track3","player3", ...] 

I would like to divide this array into two parts (almost equal) based on the number of lines (spaces here). So, for example if there is 40 spaces in this array, I need to store the lines starting from the first to the half(20th line) in a file (let's call it file A) and put the rest in file B. I could divide the arraylist, but I could not write it in the correct way in the CSV file.

我想根据行数(此处为空格)将这个数组分成两部分(几乎相等)。因此,例如,如果此数组中有 40 个空格,我需要将从第一行到一半(第 20 行)的行存储在一个文件中(我们称之为文件 A),并将其余部分放入文件 B。我可以划分数组列表,但我无法在 CSV 文件中以正确的方式写入它。

Here is my code:

这是我的代码:

public static void main(String[] args) throws java.lang.Exception { 
BufferedReader userlines = new BufferedReader(new FileReader("/..../usertrackplayer.csv"));       
FileWriter output = new FileWriter(new File("/.../output.csv"));

String uLine = null;    
ArrayList<String> list = new ArrayList<String>();
List<String> arrayList = new ArrayList<String>();
String currentUserId = null;        

while ((uLine = userlines.readLine()) != null) {

    String[] userData = uLine.split(",");
    String userId = userData[0];            
    if (userId.equals(currentUserId)) {
      // Do what ever we need while buffering same userId               
    }
    else{
        list.add(uLine);
        int division = (int) Math.ceil(list.size()/2);

        List<String> sublist = list.subList(0, division); //TO DEVIDE THE DATA OF EACH USERID INTO TWO ALMOST EQUAL PARTS, IT PUT THE FIRST HALF IN SUBLIST

     //HERE I NEED TO WRITE THE OUTPUT OF SUBLIST INTO A CSV FILE, BUT HOW????
            output.write(sublits); //--> THIS DOES NOT WORK SINCE SUBLIST IS NOT A STRING
            currentUserId = userId;
            list.clear();
    }       
     list.add(uLine);
}
    userlines.close();
    output.close();
}

Could someone please help me know how could I write the data in a list string into an empty csv file?? My second question is: how could I split them wherever there is space and consider it as a line..

有人可以帮我知道如何将列表字符串中的数据写入空的 csv 文件吗?我的第二个问题是:我怎么能在有空间的地方将它们分开并将其视为一条线..

Thanks,

谢谢,

采纳答案by pandaadb

have you considered using OpenCSV for writing your values:http://opencsv.sourceforge.net/

您是否考虑过使用 OpenCSV 来编写您的值:http://opencsv.sourceforge.net/

There is an example of how to write CSV files and it is very easy.

有一个如何编写 CSV 文件的示例,非常简单。

As to your problem, it appears you can't write the values because the Arraylist toString method will not return a comma separated string. You can use this:

至于您的问题,您似乎无法写入值,因为 Arraylist toString 方法不会返回逗号分隔的字符串。你可以使用这个:

public static void main(String[] args) throws IOException {

    FileWriter writer = new FileWriter("/Users/artur/tmp/csv/sto1.csv");

    List<String> test = new ArrayList<>();
    test.add("Word1");
    test.add("Word2");
    test.add("Word3");
    test.add("Word4");

    String collect = test.stream().collect(Collectors.joining(","));
    System.out.println(collect);

    writer.write(collect);
    writer.close();

}

See the collector impl - it will collect all String objects and concatinate them, using the separator you provide. The output then loolks like:

请参阅收集器实现 - 它将收集所有 String 对象并使用您提供的分隔符连接它们。输出看起来像:

Word1,Word2,Word3,Word4

I hope that fixes your problem. Let me know if something's not clear.

我希望能解决你的问题。如果有不清楚的地方,请告诉我。

Artur

阿图尔

Edit 2, for your question.

编辑2,针对您的问题。

If your input is a String that you read, you can split it by the space first to get it in separated lines. If it is an actual array, it won't work. This is my example:

如果您的输入是您读取的字符串,您可以先按空格将其拆分,以将其分成单独的行。如果它是一个实际的数组,它将不起作用。这是我的例子:

public static void main(String[] args) throws IOException {

        String input = "[\"user1\",\"track1\",\"player1\", \"user1\",\"track2\",\"player2\", \"user1\",\"track3\",\"player3\"]";
        input = input.substring(1, input.length() - 1); // get rid of brackets
        String[] split = input.split(" ");

        FileWriter writer = new FileWriter("/Users/artur/tmp/csv/sto1.csv");

        for(String s : split) {
            String[] split2 = s.split(",");
            writer.write(Arrays.asList(split2).stream().collect(Collectors.joining(",")));
            writer.write("\n"); // newline
        }

        writer.close();

    }

The resulting file looks like this:

生成的文件如下所示:

"user1","track1","player1"
"user1","track2","player2"
"user1","track3","player3"