Our third option to read the contents of a text file is using the Files
class of the java.nio
package. To do so, we will need to create Path
objects instead of File
objects.
Files
We can read all lines of a file at once.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class ReadAllLinesUsingFiles {
// Reads a file, line by line, using the static method readAllLines() of the {@link Files} class.
public static void main(String[] args) {
Path path = Path.of("src/main/resources/names.txt");
List<String> names = null;
try {
names = Files.readAllLines(path);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Names: " + names);
}
}
Files
We can read its whole content into a String
.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
public class ReadEntireFileUsingFiles {
// Reads the entire contents of a file using the static method readString() of the {@link Files} class.
public static void main(String[] args) {
Path path = Path.of("src/main/resources/names.txt");
List<String> names = null;
try {
String fileContent = Files.readString(path);
String[] array = fileContent.split("\n");
names = Arrays.asList(array);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Names: " + names);
}
}
Files
and a streamsWe can even use streams.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class ReadLineByLineUsingStreamFiles {
// Reads a file_manipulation.file, line by line, using the static method lines() of the {@link Files} class.
public static void main(String[] args) {
Path path = Path.of("src/main/resources/names.txt");
List<String> names = null;
try {
names = Files.lines(path).toList();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Names: " + names);
}
}
Let us revisit the athlete exercise once again. This time, you should read the athletes.data
file using the Files
class.
After solving the exercise, reflect on the 3 ways in which you read the athletes.data
file to decide which one you liked best.