Reputation:
If the lines of my file contains elements separated by comma, Can I have a buffered reader automatically plug in the elements into a list?
Or do I do a readline
then call a string.split
method?
E.g. My file has.
1, dog, abc, 10pm
2, cat, abc, 11pm
I want a list of lists out of my file so I can call the elements individually
Upvotes: 1
Views: 1055
Reputation: 17595
The interface of BufferedReader
does not support reading directly into a list and less into a list of lists. You will have at least to do the split by yourself.
As of java8
you can use BufferedReader.lines() to get stream of line which you will have to split, tranform to a list and add to a list of lists:
public List<List<String>> readAsListOfLists8(String file) throws IOException, FileNotFoundException {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
return br.lines().map(line -> Arrays.asList(line.split("[, ]+")))
.collect(Collectors.toList());
}
}
If you are running in java7
you can use Files.readAllLines to get a list of lines:
public List<List<String>> readAsListOfLists7(String file) throws IOException, FileNotFoundException {
List<List<String>> ll = new ArrayList<>();
for(String line : Files.readAllLines(Paths.get(file))) {
ll.add(Arrays.asList(line.split("[, ]+")));
}
return ll;
}
For lower versions of java use your solution.
Upvotes: 0
Reputation: 17612
The easiest thing to do for your case is to read a line first, and then use split()
, as all the lines are formatted exactly alike. And use ArrayList
of String[]
to make your list of lists.
Example using BufferedReader:
import java.util.*;
import java.io.*;
class Test {
public static void main(String[] args) {
ArrayList<ArrayList<String>> myList = new ArrayList<>();
try {
BufferedReader in = new BufferedReader(new FileReader("foo.txt"));
while(in.ready()) {
String line = in.readLine();
String[] parts = line.split(", ");
ArrayList<String> lineList = new ArrayList<>();
for (String s : parts) {
lineList.add(s);
}
myList.add(lineList);
}
}
catch(Exception e) {
}
for(ArrayList<String> elem : myList) {
for(String item : elem) {
System.out.print(item + " ");
}
System.out.println();
}
}
}
Using Scanner (incomplete example):
public static void main(String[] args) {
try {
Scanner in = new Scanner(new File("foo.txt"));
in.useDelimiter(", ");
while(in.hasNext()) {
System.out.println(in.next());
}
}
catch (Exception e) {
}
}
Upvotes: 1
Reputation: 1767
Not to my knowledge, not unless you implement your own BufferedReader... though there might be one that takes lambda in Java 8
Upvotes: 0