In Java, file handling has been made very easier and very advanced with NIO2. NIO2 stands for Non blocking Input Output version 2.
- How to read the contents of a file using Streams and NIO2 ?
The java.nio.file.Files is an helper class with many static methods that work on files or directories. Path is used to locate a file in a filesystem. Path.of(“FileName”) method is introduced in Java11. For Java8 use Path path = Paths.get(“FileName”);
Path path = Path.of("C:\\demo\\Data.txt");
try(Stream<String> lines = Files.lines(path)){
lines.filter(s -> "fruit".equalsIgnoreCase(s)).
forEach(System.out::println);
}catch(IOException e){
// log IO Exception
}
The Files.lines method (introduced in Java 11) returns a Stream of Strings that can be processed. Note that we are using try-with-resources construct for Files.lines(path) so that the underlying file resource will be closed at the end of processing.
This can be used for small or large files and it is blazing fast with a small memory footprint.
If for some reason you dont want to use streams use Files.newBufferedReader(path). This BufferedReader will be faster than using the above streams method.
try( BufferedReader bufferedReader = Files.newBufferedReader(path)){
String line = null;
while((line = bufferedReader.readLine()) != null){
if(line.equalsIgnoreCase("fruit")){
System.out.println(line);
}
}
}catch(IOException e){
//log e
}
- How to write data to a file in Java ?
The java.nio.file.Files is an helper class with many static methods that work on files or directories. Path is used to locate a file in a filesystem. Here we are using Files.newBufferedWriter(path) method.
List<String> fruits = Arrays.asList("Apple", "Orange", "Banana", "Grapes");
Path path = Path.of("C:\\demo\\DataWrite.txt");
try(BufferedWriter bufferedWriter = Files.newBufferedWriter(path) {
for(String fruit : fruits){
bufferedWriter.write(fruit);
bufferedWriter.newLine();
}
}catch(IOException e){
// log e
}
By default if the file doesn’t exist it will be created. If the file exists it will be truncated before starting to write the file.
So how to write such that contents are appended to the end of an existing file ?
Pass the StandardOpenOption.APPEND flag to Files.newBufferedWriter as shown below.
try(BufferedWriter bufferedWriter = Files.newBufferedWriter(path, StandardOpenOption.APPEND)) {