I have a csv file like this:
"user1","track1","player1"
-------------------------
"user1","track2","player2"
-------------------------
"user1","track3","player3"
-------------------------
"user1","track4","player4"
-------------------------
"user2","track2","player3"
-------------------------
.
.
"userN","trackM","playerX"
What I need to do is to divid tracks and players related to each user into a half and put them in separate files. For example, for user1, if it has 4 lines, I need to divid it into two parts (the first two lines in file A, and the rest in file B), and repeating the same action for all users. This is what I wrote so far:
public static void main(String[] args) throws java.lang.Exception {
BufferedReader userlines = new BufferedReader(new FileReader("/Users/mona/Documents/Bolzano/Datasets/Lastfm_Matthias/lastfm_usertrackplayer.csv"));
String uLine = null;
while ((uLine = userlines.readLine()) != null) {
String[] userId = uLine.split(",");
ArrayList<String> list = new ArrayList<String>();
list.add(uLine);
for(int i=0; i<=list.size();i++){
// --> THIS FOR CONDITION IS MY PROBLEM,I need s.th like for(i=0; i<=(last unique userId (i.e., length of userId[i]) until it reaches the next unique userId)
//Divide the lines and put into two separate files
}
}
userlines.close();
}
Sorry I know it should be something simple, but I really could not find any related/similar question by googling my problem :( Could someone help me please?
Thanks
You cannot know "a priori" the number of lines for each user. So you must memorize (in a List for example) all lines for the current user until you read the next user. Then save, in both files, the content of the list.
Clean the list, do the same thing for the next user.
EDIT
public static void main(String[] args) throws java.lang.Exception {
try(BufferedReader userlines = new BufferedReader(new FileReader("/Users/mona/Documents/Bolzano/Datasets/Lastfm_Matthias/lastfm_usertrackplayer.csv"));) {
String uLine = null;
ArrayList<String> list = new ArrayList<String>();
String currentUserId = null;
while ((uLine = userlines.readLine()) != null) {
String[] userData = uLine.split(",");
String userId = userData[0]; // <-- get User ID here
if (userId.equals(currentUserId)) {
// Do what ever you need while buffering same userId
} else {
// Save currentUserId in file
yourSaveMethod(list);
currentUserId = userId;
list.clear();
}
list.add(uLine);
}
}
}