Read Space-Separated Integers from a Text File
In Java, reading data from a text file can be achieved using the Files class. This tutorial demonstrates how to read integers from a text file separated by spaces and store them in an ArrayList.
Step 1: Read the Text File
Use the readAllLines() method from the Files class to load the entire text file into a List with each line represented as a String.
Step 2: Split Each Line
Apply the split() method to each line to divide it into individual integers based on the whitespace character ("s "). This creates a List of String arrays.
Step 3: Convert Strings to Integers
To convert the String representations of integers into the actual type, use the valueOf() method of the Integer class.
Step 4: Add Integers to ArrayList
Using the add() method of the ArrayList, append each integer to the list.
Step 5: Assemble the ArrayList
Combining steps 1-4, here's a comprehensive code snippet:
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); } }
Utilizing Java 8 Streams
In Java 8, the Stream API provides a more concise solution.
List<Integer> numbers = Files.lines(Paths.get("/path/to/file.txt")) .map(line -> line.split("\s+")).flatMap(Arrays::stream) .map(Integer::valueOf) .collect(Collectors.toList());
The above is the detailed content of How to Read Space-Separated Integers from a Text File in Java?. For more information, please follow other related articles on the PHP Chinese website!