java.io.File vs java.nio.Files which is the preferred in new code?

Matt Clark picture Matt Clark · Aug 21, 2015 · Viewed 13.1k times · Source

While writing answers around SO, a user tried pointing out that java.io.File should not be used in new code, instead he argues that the the new object java.nio.Files should be used instead; he linked to this article.

Now I have been developing in Java for several years now, and have not heard this argument before; since reading his post I have been searching, and have not found many other sources that confirm this, and personally, I feel like many of the points argued in the article are weak and that if you know how to read them, errors thrown by the File class will generally tell you exactly what the issue is.

As I am continually developing new code my question is this:

Is this an active argument in the Java community? Is Files preferred over File for new code? What are the major advantages / disadvantages between the two?

Answer

Jens picture Jens · Aug 21, 2015

The documentation that you linked give the answer:

The java.nio.file package defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems. This API may be used to overcome many of the limitations of the java.io.File class. The toPath method may be used to obtain a Path that uses the abstract path represented by a File object to locate a file. The resulting Path may be used with the Files class to provide more efficient and extensive access to additional file operations, file attributes, and I/O exceptions to help diagnose errors when an operation on a file fails.