Converting Pre-JDK7 File I/O Code

Prior to JDK7, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks:

  • Many methods didn't throw exceptions when they failed, so it was impossible to get a useful error message. For example, if a file delete failed, the program would receive a "delete fail" but wouldn't know if it was because the file didn't exist, the user didn't have permissions, or if there was some other problem.

  • The rename method didn't work consistently across platforms.

  • There was no real support for symbolic links.

  • More support for metadata was desired, such as file permissions, file owner and other security attributes.

  • Accessing file metadata was inefficient.

  • Many of the File methods didn't scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service.

Perhaps you have legacy code that uses java.io.File and would like to take advantage of the java.nio.file.Path functionality with minimal impact on your code.

The java.io.File class provides the toPath method that converts an oldstyle File instance to a java.nio.file.Path instance:

Path input = file.toPath();

You can then take advantage of the rich feature set available to the Path class.

For example, say you had a some code that deleted a file:

file.delete();

You can modify this code to use the Path.delete method like this:

Path fp = file.toPath();
fp.delete();

That's all you need to do!

However, if you want to take advantage of the new Path feature set, you can examine the exception to learn why the delete failed:

Path fp = file.toPath();
try {
    fp.delete();
} catch (NoSuchFileException x) {
    System.out.format("%s: no such file or directory%n", fp);
} catch (DirectoryNotEmptyException x) {
    System.out.format("%s not empty%n", fp);
} catch (IOException x) {
    //File permission problems will be caught here.
    System.out.format("%s%n", x);
}

-- Sharon Zakhour

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Blog about Java technology documentation and news about Java releases.

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today