Java: How to read a text file

Asked 2 years ago, Updated 2 years ago, 115 views

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 file

data

.
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?

java text-file file-io arraylist

2022-09-22 21:56

1 Answers

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 String to Integer using Integer#valueOf().

Integer i = Integer.valueOf(part);

Tutorial: Numbers and Strings > Converting between Numbers and Strings

You can insert data into List#add().

numbers.add(i);

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.

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);
    }
}

If you are using the Java 8 version, you can also use the Stream API that starts with 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 with Java 8 streams


2022-09-22 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.