arraylist - Java: How to read a text file -
i want read text file containing space separated values. values integers. how can read , put in array list?
here example of contents of text file:
1 62 4 55 5 6 77 i want have in arraylist [1, 62, 4, 55, 5, 6, 77]. how can in java?
you can use files#readalllines() lines of text file list<string>.
for (string line : files.readalllines(paths.get("/path/to/file.txt"))) { // ... } tutorial: basic i/o > file i/o > reading, writing , creating text files
you can use string#split() split string in parts based on regular expression.
for (string part : line.split("\\s+")) { // ... } tutorial: numbers , strings > strings > manipulating characters in string
you can use integer#valueof() convert string integer.
integer = integer.valueof(part); tutorial: numbers , strings > strings > converting between numbers , strings
you can use list#add() add element list.
numbers.add(i); tutorial: interfaces > list interface
so, in nutshell (assuming file doesn't have empty lines nor trailing/leading whitespace).
list<integer> numbers = new arraylist<>(); (string line : files.readalllines(paths.get("/path/to/file.txt"))) { (string part : line.split("\\s+")) { integer = integer.valueof(part); numbers.add(i); } } if happen @ java 8 already, can use stream api this, starting files#lines().
list<integer> numbers = files.lines(paths.get("/path/to/test.txt")) .map(line -> line.split("\\s+")).flatmap(arrays::stream) .map(integer::valueof) .collect(collectors.tolist()); tutorial: processing data java 8 streams
Comments
Post a Comment