Introduction

In this article, we discuss I/O APIs in Java 7.

I/O APIs in Java

Java provides some libraries for input/output operations, in other words reading and writing to files or network sockets. A number of key classes and packages are provided as part of the JDK for dealing with I/O in Java.
Java Packages for dealing with I/O APIs:
  1. java.io
  2. java.net
  3. java.nio

1. Java.io package

In the beginning, Java had only java.io API working with input and output operations on files. This does data stream I/O in Java applications.
It contains classes like:

2. java.net package

It provides classes to implement network-related applications.
It contains several classes:

3. Java.nio package

New I/O, also called nio, is a Java package. It was released with J2SE 1.4 used to extend the features of the java.io package. It provides low-level I/O operations on modern operating systems.
It contains several classes:
Limitation
The following are limitations of the current I/O API:
Then came Java 7 that provides a way to handle I/O operations on a file with respect to the underlying file system.
What's New
The following are what's new in the Java 7 I/O APIs:
  1. New File System API
  2. File Notifications
  3. Directory Operations
  4. Asynchronous I/0
Reasons
The following are the reasons behind the change in APIs:
1. In the previous versions, the java.io.File class is:
2. The work is done in the new I/O API provides fast and scalable I/O.
So, Java provides NIO.2, new APIs that provide better access to the FileSystem.
The new I/O API provides:
Example
Using JAVA 7 I/O API: we make a program with a .txt file to check the creation date of a file, last access of the file, last update of the file, etc.; see:
  1. import java.text.*;
  2. import java.util.*;
  3. import java.nio.file.*;
  4. import java.nio.file.attribute.*;
  5. public class Nio2Ex {
  6. public static void main(String[] args) throws Exception {
  7. FileSystem flsystem = FileSystems.getDefault();
  8. Properties pr = System.getProperties();
  9. String homePathaddress = pr.get("user.home").toString();
  10. Path homeaddress = flsystem.getPath(homePathaddress);
  11. System.out.println("File\t\t\tDate Creation \t\tLast File Access\t\tLast File Update");
  12. try (DirectoryStream < Path > flow = Files.newDirectoryStream(homeaddress, "*.txt")) {
  13. for (Path item: flow) {
  14. BasicFileAttributes atrbs = Files.readAttributes(item, BasicFileAttributes.class);
  15. Date DateCreate = new Date(atrbs.creationTime().toMillis());
  16. Date DateAccess = new Date(atrbs.lastAccessTime().toMillis());
  17. Date DateUpdate = new Date(atrbs.lastModifiedTime().toMillis());
  18. DateFormat dfrmt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
  19. System.out.format("%s\t%s\t%s\t%s%n", item, dfrmt.format(DateCreate), dfrmt.format(DateAccess), dfrmt.format(DateUpdate));
  20. }
  21. }
  22. }
  23. }
Output
pic-1.jpg