4

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.

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..

Thanks,

mOna
  • 2,341
  • 9
  • 36
  • 60

1 Answers1

17

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

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

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:

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:

Word1,Word2,Word3,Word4

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

Artur

Edit 2, for your question.

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"
pandaadb
  • 6,306
  • 2
  • 22
  • 41
  • I edited the answer to include the writing to a file bit without the opencsv library. This writes the collected string into the file. Note: I did not make it safe. You will have to wrap the writer into a try/catch/finally etc and catch edge cases, but it demonstrates the idea. – pandaadb Mar 02 '16 at 14:19
  • Thanks a lot for your great help.. it worked :) just one more question: is there any way that I could put space to specify lines in the csv? (because I need to import it into mysql later). Now my output is like: `"user1","track1","player1","user1","track2","player2","user1".... ` while I need it to be `"user1","track1","player1" "user1","track2","player2" "user1` – mOna Mar 02 '16 at 14:22
  • I added the splitting. I took your input from the question which I assume is a string you read from the input file. Splitting it by space gives you your lines. Splitting it by comma your objects. You need to write the newline to the file though to get it in lines. – pandaadb Mar 02 '16 at 14:36
  • thanks for your second answer.. actually I get error when I write `input.split` or `input.length()-1` maybe because I read my input csv file with `bufferedreader`. regarding my input file, I exported it from the mysql table which has exactly the same columns as the output file (userId, trackId, playerId).. lines are separated by space in the input file.. – mOna Mar 02 '16 at 14:44
  • I believe you will have to split/work with the uLine object in your example code. That String represents the input variable in my example. – pandaadb Mar 02 '16 at 14:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/105165/discussion-between-pandaadb-and-mona). – pandaadb Mar 02 '16 at 16:21