Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a meaningful message for failed calls to Java File objects (mkdir, rename, delete)

While using File.mkdir, and friends I notice that they don't throw exceptions on failure! Thankfully FindBugs pointed this out and now my code at least checks the return value but I still see no way to get meaningful information about why the call fails!

How do I find out why calls to these File methods fail? Is there a good alternative or library that handles this?

I've done some searches here on SO and Google and found surprising little info on this topic.

[update] I've given VFS a try and its exception don't have anymore useful information. For example trying to move a directory that had been recently deleted resulted in Could not rename file "D:\path\to\fileA" to "file:///D:/path/do/fileB". No mention that fileA no longer existed.

[update] Business requirements limit me to JDK 1.6 solutions only, so JDK 1.7 is out

like image 994
Andrew White Avatar asked Jul 20 '11 19:07

Andrew White


3 Answers

You could call native methods, and get proper error codes that way. For example, the c function mkdir has error codes like EEXIST and ENOSPC. You can use JNA to access these native functions fairly easily. If you are supporting *nix and windows you will need to create two versions of this code.

For an example of jna mkdir on linux you can do this,

import java.io.IOException;

import com.sun.jna.LastErrorException;
import com.sun.jna.Native;

public class FileUtils {

  private static final int EACCES = 13;
  private static final int EEXIST = 17;
  private static final int EMLINK = 31;
  private static final int EROFS = 30;
  private static final int ENOSPC = 28;
  private static final int ENAMETOOLONG = 63;

  static void mkdir(String path) throws IOException {

    try {
      NativeLinkFileUtils.mkdir(path);

    } catch (LastErrorException e) {
      int errno = e.getErrorCode();
      if (errno == EACCES)
        throw new IOException(
            "Write permission is denied for the parent directory in which the new directory is to be added.");
      if (errno == EEXIST)
        throw new IOException("A file named " + path + " already exists.");
      if (errno == EMLINK)
        throw new IOException(
            "The parent directory has too many links (entries).  Well-designed file systems never report this error, because they permit more links than your disk could possibly hold. However, you must still take account of the possibility of this error, as it could result from network access to a file system on another machine.");
      if (errno == ENOSPC)
        throw new IOException(
            "The file system doesn't have enough room to create the new directory.");
      if (errno == EROFS)
        throw new IOException(
            "The parent directory of the directory being created is on a read-only file system and cannot be modified.");
      if (errno == EACCES)
        throw new IOException(
            "The process does not have search permission for a directory component of the file name.");
      if (errno == ENAMETOOLONG)
        throw new IOException(
            "This error is used when either the total length of a file name is greater than PATH_MAX, or when an individual file name component has a length greater than NAME_MAX. See section 31.6 Limits on File System Capacity.");
      else
        throw new IOException("unknown error:" + errno);
    }




  }
}

class NativeLinkFileUtils {
  static {
    try {
      Native.register("c");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  static native int mkdir(String dir) throws LastErrorException;

}
like image 114
sbridges Avatar answered Oct 07 '22 07:10

sbridges


Use JDK7's new file API. It has much better OS integration and provides more detailed feedback. See the docs for moving/renaming, for example.

like image 35
Ryan Stewart Avatar answered Oct 07 '22 08:10

Ryan Stewart


You can make a utility class with some content like this:

public int mkdir(File dirToCreate) throws IOException
{
    if (dirToCreate.exists())
        throw new IOException("Folder already exists");

    if (!dirToCreate.getParent().canWrite())
        throw new IOException("No write access to create the folder");

    return dirToCreate.mkdir();
}


public int rename(File from, File to) throws IOException, FileNotFoundException
{
    if (from.equals(to))
        throw new IllegalArgumentException("Files are equal");

    if (!from.exists())
        throw new FileNotFoundException(from.getAbsolutePath() + " is not found");

    if (!to.getParent().exists())
        throw new IllegalAccessException("Parent of the destination doesn't exist");

    if (!to.getParent().canWrite())
        throw new IllegalAccessException("No write access to move the file/folder");

    return from.renameTo(to);
}

Of course this is not complete, but you can work out this idea.

like image 5
Martijn Courteaux Avatar answered Oct 07 '22 08:10

Martijn Courteaux