New IO API
In Java 8, a new IO API was introduced to provide more efficient and versatile options for handling input and output operations. This API includes classes such as InputStream, OutputStream, Reader, and Writer along with their respective subclasses and implementations.
One of the major improvements in the new IO API is the addition of try-with-resources statement, which automates the closing of resources after use. This helps in avoiding resource leaks and simplifies the code.
Here's an example that demonstrates the usage of the new IO API to read a file using the BufferedReader class:
1import java.io.BufferedReader;
2import java.io.FileReader;
3import java.io.IOException;
4
5public class NewIOAPIExample {
6
7 public static void main(String[] args) {
8 try {
9 // Creating a FileReader object
10 FileReader fileReader = new FileReader("example.txt");
11
12 // Creating a BufferedReader object
13 BufferedReader bufferedReader = new BufferedReader(fileReader);
14
15 // Reading the file line by line
16 String line;
17 while ((line = bufferedReader.readLine()) != null) {
18 System.out.println(line);
19 }
20
21 // Closing the BufferedReader
22 bufferedReader.close();
23 } catch (IOException e) {
24 e.printStackTrace();
25 }
26 }
27}In this example, we create an instance of FileReader and BufferedReader. We then use the BufferedReader object to read the contents of a file line by line and print them to the console. Finally, we close the BufferedReader in the try block using the try-with-resources statement.
The new IO API provides more flexibility and convenience for handling input and output operations in Java 8, making it easier to work with files, streams, and other sources of data.
xxxxxxxxxximport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class NewIOAPIExample { public static void main(String[] args) { try { // Creating a FileReader object FileReader fileReader = new FileReader("example.txt"); // Creating a BufferedReader object BufferedReader bufferedReader = new BufferedReader(fileReader); // Reading the file line by line String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } // Closing the BufferedReader bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } }}

