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
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;
}
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.
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.
You could execute the command and capture the err
output, which contains a meaningful message.
Here's some minimal executable code (which uses apache commons-exec) that demonstrates how this could work:
import org.apache.commons.exec.*;
public static String getErrorMessage(String command) {
CommandLine cmdLine = CommandLine.parse(command);
DefaultExecutor executor = new DefaultExecutor();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
executor.setStreamHandler(new PumpStreamHandler(out, err));
try {
executor.execute(cmdLine);
} catch (Exception e) {
return err.toString().trim();
}
return null; // no error occurred
}
Here's a test of this code showing a variety of file operation error conditions:
public static void main(String[] args) throws Exception {
System.out.println(getErrorMessage("cp fake.file x"));
System.out.println(getErrorMessage("cp /tmp /tmp"));
System.out.println(getErrorMessage("mkdir /Volumes"));
System.out.println(getErrorMessage("mv /tmp /"));
System.out.println(getErrorMessage("mv fake.file /tmp"));
}
Output (run on mac osx):
cp: fake.file: No such file or directory
cp: /tmp is a directory (not copied).
mkdir: /Volumes: File exists
mv: /tmp and /tmp are identical
mv: rename fake.file to /tmp/fake.file: No such file or directory
You could wrap the above method in a method that throws IOException that, having got the message, could parse it for the key parameters and map messages using regex matching or contains
to particular IOExceptions and throw them, eg:
if (message.endsWith("No such file or directory"))
throw new FileNotFoundException(); // Use IOExceptions if you can
if (message.endsWith("are identical"))
throw new IdenticalFileException(); // Create your own Exceptions that extend IOException
If you wanted to abstract this for use on multiple OS flavours, you would have to implement code for each platform (windows and *nix use different shell commands/error messages for any given file operation/result).
If the bounty is awarded to this answer, I'll post a complete tidy, version of working code, including a stylish enum
for file operations.
Your can use jakarta VFS instead. FileObject.createFolder()
throws FileSystemException
that holds error code. This is instead of implementing the logic offered by @Martijn Courteaux