public void exportUrlsToFile(String file, String urls) throws IOException {
String[] urlsArray = urls.split("\\s+");// split on one or more white space characters.
// create a fresh file
RandomAccessFile raf = new RandomAccessFile(file, "rw");
for (String line : urlsArray) {
line = line.trim();
if (line.isEmpty()) {// this won't happen!
continue;
}
raf.writeBytes(line);
raf.writeBytes(newline);
}
// close the file handler
raf.close();
}基本上,我使用这个类来做一些事情。这是运行在Tomcat JVM中的应用程序的一部分。我注意到,每当调用此方法时,它都会创建一个与参数同名的文件,并且在raf.close()之后,它仍然存在。如何确保删除临时文件?
发布于 2009-02-21 02:13:32
我将假设您只显示了一小部分代码,并且在没有执行任何随机访问的情况下使用RandomAccessFile是有充分理由的。
我会这样做:
public void exportUrlsToFile(String file, String urls) throws IOException {
String[] urlsArray = urls.split("\\s+");
// create a fresh file
RandomAccessFile raf = new RandomAccessFile(file, "rw");
try {
for (String line : urlsArray) {
line = line.trim();
if (line.isEmpty()) { // this won't happen!
continue;
}
raf.writeBytes(line);
raf.writeBytes(newline);
}
} finally {
// don't leak file handles on Exception -- put close in "try/finally"
try { raf.close(); } catch (IOException e) { /* ignore */ }
File todelete = new File(file);
if (!todelete.delete()) {
// Log a complaint that we couldn't delete the temp file
}
}
}编辑:我同意,我们不希望close()上的理论IOException造成问题。比忽略它更好的是写下一条“我们从未想过会看到这……”但有个例外。我经常创建一个closeWithoutException()方法来包装它。从理论上讲,抛出IOException似乎是对已检查异常的滥用,因为您不能期望调用者做出响应。
发布于 2009-02-21 01:29:22
用File.createTempFile()代替吗?
我知道这不会给你提供与RandomAccessFile相同的功能,但你可以在上面构建你需要的东西。
实际上我甚至不确定你为什么要把这些东西写到一个文件中。这是某种使用情况跟踪的东西吗?为什么不把它存储在内存中呢?
发布于 2011-07-20 17:47:02
你试过这个吗?
File temp = File.createTempFile("file", ".tmp");
temp.deleteOnExit( );https://stackoverflow.com/questions/571874
复制相似问题