In this post we will see how to search for a file in java and read the file to print its contents.
proverbs.txt is the file we are going to search and it is located in the directory D:\1\2\3
package src;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SearchAndReadFile {
private static String fileName = "proverbs.txt";
public static Path searchFile() throws IOException {
Path filePath = Paths.get("D://1");
List<Path> paths = Files.find(filePath, 3, (path, attr) -> path.toFile().getName().contains(fileName))
.collect(Collectors.toList());
paths.forEach(val -> {
System.out.println("The file path is " + val);
});
return paths.get(0);
}
public static void readFile(Path path) {
path = Paths.get(path.toUri());
Stream<String> contents = null;
try {
contents = Files.lines(path);
System.out.println("Printing the file contents......");
contents.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
} finally {
contents.close();
}
}
public static void main(String args[]) throws IOException {
readFile(searchFile());
}
}
In the above code we use Files.find() the find the exact path of the file and use the path to read the file and print its contents. The files.find() method takes following arguments
i) the starting path of the file
ii) maxDepth – the maximum number of directory levels to search
iii) matcher – the match function
In this blog using the Spring WebFlux module, we are going to leverage the functional…
Spring Cloud Function is a project within the Spring ecosystem that allows developers to build…
RabbitMQ is an open-source message broker software that implements the Advanced Message Queuing Protocol (AMQP).…
Spring Integration is a powerful extension of the Spring Framework designed to support the implementation…
The Spring Cloud Config Client is a component of the Spring Cloud framework that enables…
In Python, handling CSV (Comma Separated Values) files is easy using the built-in csv module.…