Подтвердить что ты не робот

Как получить содержательное сообщение о неудачных вызовах объектов Java File (mkdir, rename, delete)

При использовании File.mkdir и друзей я замечаю, что они не бросают исключения при отказе! К счастью, FindBugs указали это, и теперь мой код хотя бы проверяет возвращаемое значение, но я до сих пор не вижу возможности получить осмысленную информацию о том, почему вызов терпит неудачу!

Как узнать, почему вызовы этих файлов не срабатывают? Есть ли хорошая альтернатива или библиотека, которая справляется с этим?

Я сделал несколько поисков здесь, на SO и Google, и нашел удивительную небольшую информацию по этой теме.

[обновление] Я дал VFS попытку, и ее исключение больше не содержит полезной информации. Например, попытка переместить недавно удаленный каталог привела к Could not rename file "D:\path\to\fileA" to "file:///D:/path/do/fileB". Нет упоминания о том, что fileA больше не существует.

[обновление] Бизнес-требования ограничивают меня только решениями JDK 1.6, поэтому JDK 1.7 отсутствует

4b9b3361

Ответ 1

Вы можете вызвать собственные методы и получить соответствующие коды ошибок. Например, функция c mkdir содержит коды ошибок, такие как EEXIST и ENOSPC. Вы можете легко использовать JNA для доступа к этим родным функциям. Если вы поддерживаете * nix и windows, вам нужно создать две версии этого кода.

Для примера jna mkdir на linux вы можете сделать это,

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;

}

Ответ 2

Вы можете сделать класс утилиты с некоторым контентом следующим образом:

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);
}

Конечно, это не полно, но вы можете решить эту идею.

Ответ 4

Вы можете выполнить команду и захватить вывод err, содержащий содержательное сообщение.

Вот какой минимальный исполняемый код (который использует apache commons-exec), который демонстрирует, как это может работать:

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
}

Здесь тест этого кода показывает множество ошибок в работе файла:

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"));
}

Вывод (выполняется на 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

Вы можете обернуть описанный выше метод в методе, который выдает IOException, который, получив сообщение, может проанализировать его для параметров ключа и картографических сообщений, используя сопоставление регулярных выражений или contains, к определенным IOExceptions и бросить их, например:

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

Если вы хотите отвлечь его для использования на нескольких вариантах ОС, вам придется реализовать код для каждой платформы (windows и * nix используют разные команды оболочки/сообщения об ошибках для любой заданной операции файла/результата).

Если награда присуждается за этот ответ, я отправлю полную опрятную версию рабочего кода, включая стильную enum для файловых операций.