You want to read a text file with a space character delimited value. What should I do? And how do you store that read value in an array list?
For example, of the text filedata
.1 62 4 55 5 6 77
I'd like to read this data and create a pearly list like [1, 62, 4, 55, 5, 77]
. What should I do with Java?
Files#readAllLines() allows you to read the data in a text file one line at a time and save it as
List<String>
.
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
// ...
}
Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files
String#split()
can be used to truncate String
based on regular expressions.
for (String part : line.split("\\s+")) {
// ...
}
Tutorial: Numbers and Strings > Manipulating Characters in a String
You can convert Tutorial: Numbers and Strings > Converting between Numbers and Strings Tutorial: Interfaces > The List Interface So, in summary, you can: However, the file must have at least one string. White space must not exist before and after the file. If you are using the Java 8 version, you can also use the Stream API that starts with Tutorial: Processing data with Java 8 streams
String
to Integer
using Integer#valueOf(). p>
Integer i = Integer.valueOf(part);
List#add()
.numbers.add(i);
List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
for (String part : line.split("\\s+")) {
Integer i = Integer.valueOf(part);
numbers.add(i);
}
}
Files#lines(). p>
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());
© 2024 OneMinuteCode. All rights reserved.