I have a file.txt
:
100
120 200 10
105 12 25
And I'd like to make arraylists like this
[100]
[120, 200, 10]
[105, 12, 25]
What do I do with basic Java knowledge?
I have a file.txt
:
100
120 200 10
105 12 25
And I'd like to make arraylists like this
[100]
[120, 200, 10]
[105, 12, 25]
What do I do with basic Java knowledge?
Assuming you want each ArrayList<String>
or ArrayList<Integer>
to be per line, then you can simply iterate through the file line-by-line and split each line against whitespace:
Files.lines(Paths.get("file.txt"))
.map(line -> line.split(" "))
.map(List::of)
.collect(Collectors.toCollection(ArrayList::new));
This returns an unmodifiable ArrayList<List<String>>
, but you can easily modify it to whatever type you want (if you tell me what type, I'll modify it for you!).
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
List<String> list = new ArrayList<String>(Arrays.asList(string.split(" ")));
// now you can do something with `list`
}
}
In short: Read file, read line, split line content by spaces, and the splitting will actually give you an array back.
Its really simple, in fact, with basic Java knowledge (as you mentioned) there would be no need to ask help. Especially considering this looks like school homework and you want a quick answer without investing time yourself :)