java每日一学--IO
规则3.1 临时文件使用完毕应及时删除
说明:临时文件可能包含敏感数据,为防止可能的未授权访问,需保证临时文件在使用完毕前被删除。错误示例:在结束时没有删除创建的临时文件。
public class TempFile { public static void main(String[] args) throws IOException { File f = new File("tempnam.tmp"); if (f.exists()) { System.out.println("This file already exists"); return; } FileOutputStream fop = null; try { fop = new FileOutputStream(f); String str = "Data"; fop.write(str.getBytes()); } finally { if (fop != null) { try { fop.close(); } catch (IOException x) { // handle error } } } } } 推荐做法1: public class TempFile { public static void main(String[] args) { Path tempFile = null; try { tempFile = Files.createTempFile("tempnam", ".tmp"); try (BufferedWriter writer = Files.newBufferedWriter(tempFile, Charset.forName("UTF8"), StandardOpenOption.DELETE_ON_CLOSE)) { // write to file } System.out.println("Temporary file write done, file erased"); } catch (FileAlreadyExistsException x) { System.err.println("File exists: " + tempFile); } catch (IOException x) { // Some other sort of failure, such as permissions. System.err.println("Error creating temporary file: " + x); } } }
该示例代码使用了 Java SE 7 的 NIO2 包中的几个方法创建了一个临时文件,使用的是 createTempFile()
方法,
它创建一个不可预知的名字。使用try-with-resources结构打开文件,不管是否有异常该结构都会自动关闭文件。最
后,文件是用 Java SE 7 的 DELETE_ON_CLOSE
选项打开的,这使得在文件关闭时自动删除。如果是jdk1.7之前的
版本,则需在临时文件使用之后主动删除。
推荐做法2:
public class TempFile { public static void main(String[] args) throws IOException { File f = File.createTempFile("tempnam", ".tmp"); FileOutputStream fop = null; try { fop = new FileOutputStream(f); String str = "Data"; fop.write(str.getBytes()); fop.flush(); } finally { if (fop != null) { try { fop.close(); f.delete(); //delete file when finished } catch (IOException x) { // handle error } } } } } 如果使用的是JDK1.7之前的版本,可以自己编写代码实现临时文件在使用完之后对其进行删除。