看别人的程序,在更新 xml 文件的时候,是先 创建一个临时文件,把新数据写入这个临时文件,说是为了最大化安全。最后再把原文件删除,更新临时文件名为原文件名,所谓“安全”, 是担心写磁盘xml文件的时候出现某故障,导致 xml 文件格式出问题吗 ? 
  部分代码如下: 
   
  /** 
     * Saves the properties to disk as an XML document. A temporary file is 
     * used during the writing process for maximum safety. 
     */ 
    private synchronized void saveProperties() { 
        OutputStream out = null; 
        boolean error = false; 
        // Write data out to a temporary file first. 
        File tempFile = null; 
        try { 
            tempFile = new File(file.getParentFile(), file.getName() + ".tmp"); 
            // Use JDOM's XMLOutputter to do the writing and formatting. The 
            // file should always come out pretty-printed. 
            XMLOutputter outputter = new XMLOutputter("    ", true); 
            out = new BufferedOutputStream(new FileOutputStream(tempFile)); 
            outputter.output(doc, out); 
        } 
        catch (Exception e) { 
            e.printStackTrace(); 
            // There were errors so abort replacing the old property file. 
            error = true; 
        } 
        finally { 
            try {  out.close();  } 
            catch (Exception e) { 
                e.printStackTrace(); 
                error = true; 
            } 
        } 
        // No errors occured, so we should be safe in replacing the old 
        if (!error) { 
            // Delete the old file so we can replace it. 
            file.delete(); 
            // Rename the temp file. The delete and rename won't be an 
            // automic operation, but we should be pretty safe in general. 
            // At the very least, the temp file should remain in some form. 
            tempFile.renameTo(file); 
        } 
    }