gpt4 book ai didi

java - 如何为 Java 文件对象(mkdir、重命名、删除)调用失败获取有意义的消息

转载 作者:搜寻专家 更新时间:2023-10-30 19:53:47 25 4
gpt4 key购买 nike

在使用 File.mkdir 时,我注意到 friend 们在失败时不会抛出异常!值得庆幸的是,FindBugs 指出了这一点,现在我的代码至少检查了返回值,但我仍然看不到有关为什么调用失败的有意义的信息!

如何找出对这些 File 方法的调用失败的原因?有没有好的替代方案或库来处理这个问题?

我在 SO 和 Google 上进行了一些搜索,发现关于这个主题的信息很少。

[更新] 我尝试了 VFS,但它的异常没有更多有用的信息。例如,尝试移动最近删除的目录导致 Could not rename file "D:\path\to\fileA"to "file:///D:/path/do/fileB". 没有提到 fileA 不再存在。

[更新] 业务需求限制我只能使用 JDK 1.6 解决方案,因此 JDK 1.7 已经过时了

最佳答案

您可以调用 native 方法,并以这种方式获得正确的错误代码。例如,c 函数 mkdir有类似 EEXIST 和 ENOSPC 的错误代码。您可以使用 JNA相当容易地访问这些 native 功能。如果您支持 *nix 和 Windows,则需要创建此代码的两个版本。

对于 linux 上的 jna mkdir 示例,您可以这样做,

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;

}

关于java - 如何为 Java 文件对象(mkdir、重命名、删除)调用失败获取有意义的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6767382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com