是否有一种标准且可靠的方法可以在 Java 应用程序中创建临时目录?Java 的问题数据库中有一个条目,注释中有一些代码,但我想知道在常用库之一(Apache Commons 等)中是否有标准解决方案?
如果您使用的是 JDK 7,请使用新的 Files.createTempDirectory 类来创建临时目录。
Path tempDirWithPrefix = Files.createTempDirectory(prefix);
在 JDK 7 之前,这应该这样做:
public static File createTempDirectory()
throws IOException
{
final File temp;
temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
if(!(temp.delete()))
{
throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
}
if(!(temp.mkdir()))
{
throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
}
return (temp);
}
如果需要,您可以创建更好的例外(子类 IOException)。
谷歌番石榴库有大量有用的实用程序。这里值得注意的是文件类。它有很多有用的方法,包括:
File myTempDir = Files.createTempDir();
这完全符合您在一行中的要求。如果您阅读此处的文档,您会发现建议的改编通常会引入安全漏洞。File.createTempFile("install", "dir")
如果你需要一个临时目录进行测试,并且你正在使用jUnit,以及解决你的问题:@Rule
TemporaryFolder
@Rule
public TemporaryFolder folder = new TemporaryFolder();
从文档中:
临时文件夹规则允许创建保证在测试方法完成时删除的文件和文件夹(无论测试通过还是失败)
更新:
如果您使用的是 JUnit Jupiter(版本 5.1.1 或更高版本),则可以选择使用 JUnit Pioneer,即 JUnit 5 扩展包。
从项目文档复制:
例如,以下测试注册单个测试方法的扩展名,创建文件并将其写入临时目录并检查其内容。
@Test
@ExtendWith(TempDirectory.class)
void test(@TempDir Path tempDir) {
Path file = tempDir.resolve("test.txt");
writeFile(file);
assertExpectedFileContent(file);
}
更多信息在 JavaDoc 和 JavaDoc 的 TempDirectory
格拉德尔:
dependencies {
testImplementation 'org.junit-pioneer:junit-pioneer:0.1.2'
}
专家:
<dependency>
<groupId>org.junit-pioneer</groupId>
<artifactId>junit-pioneer</artifactId>
<version>0.1.2</version>
<scope>test</scope>
</dependency>
更新 2:
@TempDir注释作为实验性功能添加到 JUnit Jupiter 5.4.0 版本中。从 JUnit 5 用户指南复制的示例:
@Test
void writeItemsToFile(@TempDir Path tempDir) throws IOException {
Path file = tempDir.resolve("test.txt");
new ListWriter(file).write("a", "b", "c");
assertEquals(singletonList("a,b,c"), Files.readAllLines(file));
}
模板简介:该模板名称为【Java 如何在 Java 中创建临时目录/文件夹】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Java】栏目查找您需要的精美模板。