Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to read a text file

I want to read a text file containing space separated values. Values are integers. How can I read it and put it in an array list?

Here is an example of contents of the text file:

1 62 4 55 5 6 77 

I want to have it in an arraylist as [1, 62, 4, 55, 5, 6, 77]. How can I do it in Java?

like image 260
aks Avatar asked May 07 '10 11:05

aks


People also ask

Can we read file in java?

The canRead()function is a part of the File class in Java. This function determines whether the program can read the file denoted by the abstract pathname. The function returns true if the abstract file path exists and the application is allowed to read the file.

How do you load a file in java?

Example 1: Java Program to Load a Text File as InputStream txt. Here, we used the FileInputStream class to load the input. txt file as input stream. We then used the read() method to read all the data from the file.


1 Answers

You can use Files#readAllLines() to get all lines of a text file into a 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


You can use String#split() to split a String in parts based on a regular expression.

for (String part : line.split("\\s+")) {     // ... } 

Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String


You can use Integer#valueOf() to convert a String into an Integer.

Integer i = Integer.valueOf(part); 

Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings


You can use List#add() to add an element to a List.

numbers.add(i); 

Tutorial: Interfaces > The List Interface


So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).

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 happen to be at Java 8 already, then you can even use Stream API for this, starting 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

like image 64
BalusC Avatar answered Sep 22 '22 12:09

BalusC