gpt4 book ai didi

Java7/枚举构造函数/Files.createTempDirectory(String prefix, FileAttribute... attrs)

转载 作者:行者123 更新时间:2023-11-30 04:57:07 24 4
gpt4 key购买 nike

我想为枚举构造函数创建一个 Path 实例:

/** Temporary paths. */
public enum PATHS {

/** First temporary directory. */
PATH1(Files.createTempDirectory(new StringBuilder("tnk").append(File.separator).append("path1")
.toString())),
/** Second temporary directory. */
PATH2(Files.createTempDirectory(new StringBuilder("tnk").append(File.separator).append("path2")
.toString()));

/** {@link Path} reference. */
final Path mPath;

/**
* Constructor.
*
* @param pPath
* {@link Path} reference
*/
PATHS(final Path pPath) {
mPath = pPath;
}

/**
* Get {@link File} associated with the path.
*
* @return {@link File} reference
*/
public File getFile() {
return mPath.toFile();
}
}

Files.createTempDirectory(String, FilleAttribute<?> atts)抛出一个已检查的异常(IOException),但是如何捕获或抛出该异常,或者更准确地说,如何处理该异常?似乎是一个转储问题,但我现在不知道。

最佳答案

改为在构造函数中处理它。

PATH1("path1"),
PATH2("path2");

final Path mPath;

PATHS(final String path) {
try {
mPath = Files.createTempDirectory(new StringBuilder("tnk").append(File.separator).append(path).toString());
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
}
}

额外的好处是,它还可以最大限度地减少这种特殊情况下的代码重复。

话虽如此,我真的会仔细考虑 Tom Hawtin 想要告诉你的内容。

关于Java7/枚举构造函数/Files.createTempDirectory(String prefix, FileAttribute<?>... attrs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8173038/

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