Home > Java > javaTutorial > How to Read Space-Separated Integers from a Text File in Java?

How to Read Space-Separated Integers from a Text File in Java?

Susan Sarandon
Release: 2024-12-09 22:00:19
Original
871 people have browsed it

How to Read Space-Separated Integers from a Text File in Java?

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);
    }
}
Copy after login

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());
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template