如何renameFile

 

Lucene的文件改名函数, renameTo()方法在JVM中是不稳定的,所以若失败则采用文件内容拷贝,删除原文件。拷贝采用字节流。

//lucene-2.0.0 FSDirectory.java

File directory;

/** Renames an existing file in the directory. */
public synchronized void renameFile(String from, String to)
     throws IOException {
   File old = new File(directory, from);
   File nu = new File(directory, to);

   /* This is not atomic.  If the program crashes between the call to
      delete() and the call to renameTo() then we're screwed, but I've
      been unable to figure out how else to do this... */

   if (nu.exists())
     if (!nu.delete())
       throw new IOException("Cannot delete " + nu);

   // Rename the old file to the new one. Unfortunately, the renameTo()
   // method does not work reliably under some JVMs.  Therefore, if the
   // rename fails, we manually rename by copying the old file to the new one
   if (!old.renameTo(nu)) {
     java.io.InputStream in = null;
     java.io.OutputStream out = null;
     try {
       in = new FileInputStream(old);
       out = new FileOutputStream(nu);
       // see if the buffer needs to be initialized. Initialization is
       // only done on-demand since many VM's will never run into the renameTo
       // bug and hence shouldn't waste 1K of mem for no reason.
       if (buffer == null) {
         buffer = new byte[1024];
       }
       int len;
       while ((len = in.read(buffer)) >= 0) {
         out.write(buffer, 0, len);
       }

       // delete the old file.
       old.delete();
     }
     catch (IOException ioe) {
       IOException newExc = new IOException("Cannot rename " + old + " to " + nu);
       newExc.initCause(ioe);
       throw newExc;
     }
     finally {
       if (in != null) {
         try {
           in.close();
         } catch (IOException e) {
           throw new RuntimeException("Cannot close input stream: " + e.toString(), e);
         }
       }
       if (out != null) {
         try {
           out.close();
         } catch (IOException e) {
           throw new RuntimeException("Cannot close output stream: " + e.toString(), e);
         }
       }
     }
   }
}

你可能感兴趣的:(职场,休闲,renameFile)