对于我的应用程序,我必须编写一个采用InputStream
as 参数的方法,将内容写入临时文件,执行一些操作并最终删除临时文件。
这是我到目前为止所拥有的:
public void myMethod(InputStream in, String name) {
//...
Path path = Paths.get("./tmp/benchmarks/" + name + ".zip")
try {
Files.copy(in, path);
//operations...
} catch (IOException e) {
//error handling for copy...
} finally {
try {
Files.delete(path));
} catch (IOException e) {
//error handling for delete...
}
}
//...
}
它可以完成这项工作,但它看起来也很丑陋。我想知道是否有某种方法可以try-with-resources
更优雅地处理这个问题。有可能吗?
更新:我在十分钟内写了一个即时解决方案。它看起来像这样:
public class TemporaryFileHandler implements AutoCloseable {
private File file;
public TemporaryFileHandler(final InputStream in, final Path path) throws IOException {
Files.copy(in, path);
this.file = new File(path.toString());
}
public File getFile() { return file; }
@Override
public void close() throws IOException {
Files.delete(file.toPath());
}
}
我确信这不是最好的,但它现在可以完成工作。如果有人对如何以任何方式改进这一点有任何建议,我们非常欢迎提出建议。