I'm reading from a text file (usernames.txt
) which has values separated by commas:
AA328747, AA337748, AA057393, AA290457, AA467620, AA225950, AA352105, AA108183, AA057070,
using my method:
public static List<String> readUsername(String path){
File file = new File(path);
Reader fileReader;
List<String> list = new ArrayList<String>();
String username;
try
{
fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
username = br.readLine();
while (username != null)
{
list.add(username);
username= br.readLine();
}
br.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return list;
}
And I try to print it out to console:
List<String> usernameList = readUsername(fileStr);
for (int i=0; i < usernameList.size(); i++)
{
System.out.println(usernameList.size());
System.out.println(usernameList.get(i) + " end");
}
where fireStr
is just my path file string.
And it prints well but the size of the list object (usernameList.size()
) is only 1
.
The print out is:
AA328747, AA337748, AA057393, AA290457, AA467620, AA225950, AA352105, AA108183, AA057070, end
How I want it to print out is like:
AA328747 end
AA337748 end
AA057393 end
AA290457 end
AA467620 end
AA225950 end
AA352105 end
AA108183 end
AA057070 end
And the list size should be more than 1
items (In my example it should be 9
for nine usernames in the text file).
How do I get rid of the commas and just evaluate each username as separate strings instead of one big string?
I believe you want the split()
method. You can use Collections#addAll
to directly add all the elements from the Array
produced by split
to the List
:
while (username != null)
{
Collections.addAll(list, username.split(","));
username= br.readLine();
}