如何在Java中创建临时目录/文件夹?是否有一种在Java应用程序中创建临时目录的标准且可靠的方法?Java的问题数据库中有一个条目,在评论中有一些代码,但我想知道是否有一个标准的解决方案可以在其中一个常见的库(Apache Commons等)中找到?
3 回答

梦里花落0921
TA贡献1772条经验 获得超6个赞
如果您使用的是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)。
添加回答
举报
0/150
提交
取消