Reputation: 25
I have a file where I get to read it's content. Now I would like to split each seperate line into an arrayList individually and cant succeed.
This is what I have so far
try {
input = new FileInputStream(test);
byte testContent[] = new byte[(int) test.length()];
input.read(testContent);
String testFile = new String(testContent);
System.out.println(testFile);
}
An example of file content is as follows,
0,0,5,13,9,1,0,0,0,0,13,15,10,15,5,0,0,3,15,2,0,11,8,0,0,4,12,0,0,8,8,0,0,5,8,0
0,0,0,12,13,5,0,0,0,0,0,11,16,9,0,0,0,0,3,15,16,6,0,0,0,7,15,16,16,2,0,0,0,0,1,1
0,0,0,4,15,12,0,0,0,0,3,16,15,14,0,0,0,0,8,13,8,16,0,0,0,0,1,6,15,11,0,0,0,1,8,1
0,0,7,15,13,1,0,0,0,8,13,6,15,4,0,0,0,2,1,13,13,0,0,0,0,0,2,15,11,1,0,0,0,0,0,1
0,0,0,1,11,0,0,0,0,0,0,7,8,0,0,0,0,0,1,13,6,2,2,0,0,0,7,15,0,9,8,0,0,5,16,10,0,1
I would like the above to be in arrays like
[0,0,5,13,9,1,0,0,0,0,13,15,10,15,5,0,0,3,15,2,0,11,8,0,0,4,12,0,0,8,8,0,0,5,8,0]
[0,0,0,12,13,5,0,0,0,0,0,11,16,9,0,0,0,0,3,15,16,6,0,0,0,7,15,16,16,2,0,0,0,0,1,1]
[0,0,0,4,15,12,0,0,0,0,3,16,15,14,0,0,0,0,8,13,8,16,0,0,0,0,1,6,15,11,0,0,0,1,8,1]
[0,0,7,15,13,1,0,0,0,8,13,6,15,4,0,0,0,2,1,13,13,0,0,0,0,0,2,15,11,1,0,0,0,0,0,1]
[0,0,0,1,11,0,0,0,0,0,0,7,8,0,0,0,0,0,1,13,6,2,2,0,0,0,7,15,0,9,8,0,0,5,16,10,0,1]
Thanks in advance for any help
Upvotes: 0
Views: 83
Reputation: 529
You can try something like this:
BufferedReader br = new BufferedReader(new FileReader(yourFile));
List<String[]> listOfArrays = new ArrayList<String[]>();
String nextLine;
while((nextLine = br.readLine()) != null){
String[] lineArray = nextLine.split(",");
listOfArrays.add(lineArray);
}
Upvotes: 0
Reputation: 50716
How about Files.readAllLines()
:
List<String> lines = Files.readAllLines(new File(test).toPath());
If you're using Java 7, you'll need this version:
List<String> lines = Files.readAllLines(new File(test).toPath(), StandardCharsets.UTF_8);
Upvotes: 1
Reputation: 2153
Use String#split()
String[] strings= testFile.split("\\r?\\n");
List<String> list = Arrays.asList(strings);
You can have more details about this method from this question How to split a string in Java
Upvotes: 0