0

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?

takendarkk
  • 2,949
  • 7
  • 22
  • 35
  • 2
    Have you tried _anything_ yet? – takendarkk Feb 01 '18 at 16:53
  • Try looking to [`BufferedReader`](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html) and [`String.split(String)`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-) – phflack Feb 01 '18 at 16:53
  • [Reading a plain text file in Java](https://stackoverflow.com/q/4716503/5475891) and [How to convert comma-separated String to ArrayList?](https://stackoverflow.com/q/7488643/5475891), – phflack Feb 01 '18 at 16:56
  • Break it down. How do you open a file for reading? How do you read lines from that file? How do you split each line? How do you add each of those splits into a list-of-lists? Each of these is a task in itself (and have been covered already on this site). – yshavit Feb 01 '18 at 16:57

3 Answers3

3

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!).

jihor
  • 2,138
  • 11
  • 24
Jacob G.
  • 26,421
  • 5
  • 47
  • 96
  • While useful, I wouldn't quite put this in the realm of "basic Java knowledge". I do enjoy seeing how java8 streams change things – phflack Feb 01 '18 at 16:58
  • That's true, I didn't see where it said "basic Java knowledge". I'll delegate to Ben's answer then, even though I can argue that it's still somewhat advanced: https://stackoverflow.com/a/48567969/7294647 – Jacob G. Feb 01 '18 at 17:00
1
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`
    }
}
Ben Harris
  • 537
  • 5
  • 10
0

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 :)

Chapz
  • 477
  • 4
  • 11