java.io.File#renameTo ( )源码实例Demo

下面列出了java.io.File#renameTo ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Alite   文件: DownloadThread.java
/**
 * Called after a successful completion to take any necessary action on the
 * downloaded file.
 */
private void finalizeDestinationFile(State state) throws StopRequest {
    syncDestination(state);
    String tempFilename = state.mFilename;
    String finalFilename = Helpers.generateSaveFileName(mService, mInfo.mFileName);
    if (!state.mFilename.equals(finalFilename)) {
        File startFile = new File(tempFilename);
        File destFile = new File(finalFilename);
        if (mInfo.mTotalBytes != -1 && mInfo.mCurrentBytes == mInfo.mTotalBytes) {
            if (!startFile.renameTo(destFile)) {
                throw new StopRequest(DownloaderService.STATUS_FILE_ERROR,
                        "unable to finalize destination file");
            }
        } else {
            throw new StopRequest(DownloaderService.STATUS_FILE_DELIVERED_INCORRECTLY,
                    "file delivered with incorrect size. probably due to network not browser configured");
        }
    }
}
 
源代码2 项目: sofa-acts   文件: FileOperateUtils.java
/**
 *
 * @param fromFile
 * @param newName
 * @return
 * @author mokong
 */
public static boolean renameFile(File fromFile, String newName) {

    String orgiFilePath = fromFile.getParent();
    File newFile = new File(orgiFilePath + "/" + newName);

    if (newFile.exists() && newFile.delete()) {
        log.error(newFile.getAbsolutePath() + " delete sucessfully");
    }

    if (fromFile.renameTo(newFile)) {
        log.error(fromFile.getName() + " rename to " + newFile.getName() + "sucessfully");
        return true;
    } else {
        log.error(fromFile.getName() + " rename to" + newFile.getName() + "failed");
        return false;
    }

}
 
源代码3 项目: olat   文件: LocalFolderImpl.java
/**
*/
  @Override
  public VFSStatus rename(String newname) {
      File f = getBasefile();
      File par = f.getParentFile();
      File nf = new File(par, newname);
      VersionsManager.getInstance().rename(this, newname);
      boolean ren = f.renameTo(nf);
      if (ren) {
          // f.renameTo() does NOT modify the path contained in the object f!!
          // The guys at sun consider this a feature and not a bug...
          // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4094022
          // We need to manually reload the new basefile and set it in our parent
          super.setBasefile(new File(nf.getAbsolutePath()));
          return VFSConstants.YES;
      } else {
          return VFSConstants.NO;
      }
      // FIXME notify children that a parent has been renamed?
  }
 
源代码4 项目: fabric8-forge   文件: RepositoryResource.java
protected CommitInfo doRename(Git git, String oldPath, String newPath) throws Exception {
    File file = getRelativeFile(oldPath);
    File newFile = getRelativeFile(newPath);
    if (file.exists()) {
        File parentFile = newFile.getParentFile();
        parentFile.mkdirs();
        if (!parentFile.exists()) {
            throw new IOException("Could not create directory " + parentFile + " when trying to move " + file + " to " + newFile + ". Maybe a file permission issue?");
        }
        file.renameTo(newFile);
        String filePattern = getFilePattern(newPath);
        git.add().addFilepattern(filePattern).call();
        CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message);
        return createCommitInfo(commitThenPush(git, commit));
    } else {
        return null;
    }
}
 
源代码5 项目: hadoop   文件: NativeIO.java
/**
 * A version of renameTo that throws a descriptive exception when it fails.
 *
 * @param src                  The source path
 * @param dst                  The destination path
 * 
 * @throws NativeIOException   On failure.
 */
public static void renameTo(File src, File dst)
    throws IOException {
  if (!nativeLoaded) {
    if (!src.renameTo(dst)) {
      throw new IOException("renameTo(src=" + src + ", dst=" +
        dst + ") failed.");
    }
  } else {
    renameTo0(src.getAbsolutePath(), dst.getAbsolutePath());
  }
}
 
源代码6 项目: MyBox   文件: ImageViewerController.java
public File renameFile(File sfile) {
    if (sfile == null) {
        return null;
    }
    try {
        final File file = chooseSaveFile(AppVariables.getUserConfigPath(targetPathKey),
                null, CommonFxValues.ImageExtensionFilter, true);
        if (file == null) {
            return null;
        }
        recordFileWritten(file);

        if (file.exists()) {
            if (!file.delete()) {
                popFailed();
            }
        }
        if (sfile.renameTo(file)) {
            popSuccessful();
            return file;
        } else {
            popFailed();
            return null;
        }

    } catch (Exception e) {
        logger.error(e.toString());
        return null;
    }

}
 
源代码7 项目: ResearchStack   文件: FileUtils.java
public static void writeSafe(File file, byte[] data) {
    try {
        File tempFile = makeTempFile(file);
        FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
        fileOutputStream.write(data);
        fileOutputStream.close();
        tempFile.renameTo(file);
    } catch (IOException e) {
        throw new StorageAccessException(e);
    }
}
 
源代码8 项目: star-zone-android   文件: FileUtil.java
/**
 * 先改名,在删除(为了避免EBUSY (Device or resource busy)的错误)
 */
private static void safelyDelete(File file) {
    if (file == null || !file.exists()) return;
    try {
        final File to = new File(file.getAbsolutePath() + System.currentTimeMillis());
        file.renameTo(to);
        to.delete();
    } catch (Exception e) {
        KLog.e(e);
    }
}
 
源代码9 项目: knox   文件: GatewayServer.java
private void handleCreateDeployment(Topology topology, File deployDir) {
      try {
        File topoDir = calculateDeploymentDir( topology );
        if( !topoDir.exists() ) {
          auditor.audit( Action.DEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.UNAVAILABLE );

//          KNOX-564 - Topology should fail to deploy with no providers configured.
//TODO:APPS:This should only fail if there are services in the topology.
          if(topology.getProviders().isEmpty()) {
            throw new DeploymentException("No providers found inside topology.");
          }

          log.deployingTopology( topology.getName(), topoDir.getAbsolutePath() );
          internalDeactivateTopology( topology ); // KNOX-152

          EnterpriseArchive ear = DeploymentFactory.createDeployment( config, topology );
          if( !deployDir.exists() && !deployDir.mkdirs() ) {
            throw new DeploymentException( "Failed to create topology deployment temporary directory: " + deployDir.getAbsolutePath() );
          }
          File tmp = ear.as( ExplodedExporter.class ).exportExploded( deployDir, topoDir.getName() + ".tmp" );
          if( !tmp.renameTo( topoDir ) ) {
            FileUtils.deleteQuietly( tmp );
            throw new DeploymentException( "Failed to create topology deployment directory: " + topoDir.getAbsolutePath() );
          }
          internalDeployApplications( topology, topoDir );
          internalActivateTopology( topology, topoDir );
          log.deployedTopology( topology.getName());
        } else {
          auditor.audit( Action.REDEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.UNAVAILABLE );
          log.redeployingTopology( topology.getName(), topoDir.getAbsolutePath() );
          internalActivateTopology( topology, topoDir );
          log.redeployedTopology( topology.getName() );
        }
        cleanupTopologyDeployments( deployDir, topology );
      } catch( Throwable e ) {
        auditor.audit( Action.DEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE );
        log.failedToDeployTopology( topology.getName(), e );
      }
    }
 
源代码10 项目: cwac-saferoom   文件: SQLCipherUtils.java
/**
 * Replaces this database with a decrypted version, deleting the original
 * encrypted database. Do not call this while the database is open, which
 * includes during any Room migrations.
 *
 * The passphrase is untouched in this call. Please set all bytes of the
 * passphrase to 0 or something to clear out the passphrase if you are done
 * with it.
 *
 * @param ctxt a Context
 * @param originalFile a File pointing to the encrypted database
 * @param passphrase the passphrase from the user for the encrypted database
 * @throws IOException
 */
public static void decrypt(Context ctxt, File originalFile, byte[] passphrase)
  throws IOException {
  SQLiteDatabase.loadLibs(ctxt);

  if (originalFile.exists()) {
    File newFile=
      File.createTempFile("sqlcipherutils", "tmp",
        ctxt.getCacheDir());
    SQLiteDatabase db=
      SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(),
        passphrase, null, SQLiteDatabase.OPEN_READWRITE, null, null);

    final SQLiteStatement st=db.compileStatement("ATTACH DATABASE ? AS plaintext KEY ''");

    st.bindString(1, newFile.getAbsolutePath());
    st.execute();

    db.rawExecSQL("SELECT sqlcipher_export('plaintext')");
    db.rawExecSQL("DETACH DATABASE plaintext");

    int version=db.getVersion();

    st.close();
    db.close();

    db=SQLiteDatabase.openDatabase(newFile.getAbsolutePath(), "",
      null, SQLiteDatabase.OPEN_READWRITE);
    db.setVersion(version);
    db.close();

    originalFile.delete();
    newFile.renameTo(originalFile);
  }
  else {
    throw new FileNotFoundException(originalFile.getAbsolutePath()+" not found");
  }
}
 
源代码11 项目: 365browser   文件: CrashFileManager.java
/**
 * Renames a crash dump file. However, if renaming fails, attempts to delete the file
 * immediately.
 */
private static void renameCrashDumpFollowingUpload(File crashDumpFile, String suffix) {
    // The pre-upload filename might have been either "foo.dmpN.tryM" or "foo.forcedN.tryM".
    String newName = crashDumpFile.getPath()
                             .replace(NOT_YET_UPLOADED_MINIDUMP_SUFFIX, suffix)
                             .replace(UPLOAD_FORCED_MINIDUMP_SUFFIX, suffix);
    boolean renamed = crashDumpFile.renameTo(new File(newName));
    if (!renamed) {
        Log.w(TAG, "Failed to rename " + crashDumpFile);
        if (!crashDumpFile.delete()) {
            Log.w(TAG, "Failed to delete " + crashDumpFile);
        }
    }
}
 
源代码12 项目: ARMStrong   文件: SVCCallRename.java
@Override
protected void primitive() {
	try {
		int originalLength = this.getRam().getValue(this.getCpu().getRegister(1).getValue()+4);
		int newLength = this.getRam().getValue(this.getCpu().getRegister(1).getValue()+12);
		String originalName = this.longToString(this.getRam().getValue(this.getCpu().getRegister(1).getValue()), originalLength);
		String newName = this.longToString(this.getRam().getValue(this.getCpu().getRegister(1).getValue())+8, newLength);
		
		File file = new File(originalName);
		boolean success = file.renameTo(new File(newName));
		this.getCpu().getRegister(0).setValue(success ? 0 : -1);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
public static FileBasedCachingEntityCheckerManager create(long cacheEntryLifetime, File cacheFile) {
    File tempCacheFile = new File(cacheFile.getAbsolutePath() + "_temp");

    ObjectLongOpenHashMap<String> cache = null;
    // try to read the cache file
    cache = readCacheFile(cacheFile);
    // if this doesn't work, try to read the temp file
    if (cache == null) {
        LOGGER.warn("Couldn't read the cache file. Trying the temporary file...");
        cache = readCacheFile(tempCacheFile);
        // if this worked, rename the temp file to the real file
        if (cache != null) {
            try {
                if (!tempCacheFile.renameTo(cacheFile)) {
                    LOGGER.warn("Reading from the temporary cache file worked, but I couldn't rename it.");
                }
            } catch (Exception e) {
                LOGGER.warn("Reading from the temporary cache file worked, but I couldn't rename it.", e);
            }
        }
    }
    // if the reading didn't worked, create new cache objects
    if (cache == null) {
        LOGGER.warn("Couldn't read cache from files. Creating new empty cache.");
        cache = new ObjectLongOpenHashMap<String>();
    }
    return new FileBasedCachingEntityCheckerManager(cache, cacheEntryLifetime, cacheFile, tempCacheFile);
}
 
源代码14 项目: QSVideoPlayer   文件: FileUtil.java
/**
 * 重命名
 */
public boolean renameFile(String oldname, String newname) {
    File oldfile = new File(oldname);
    File newfile = new File(newname);
    if (oldname.equals(newname) || newfile.exists() || !oldfile.exists())
        return false;
    return oldfile.renameTo(newfile);
}
 
源代码15 项目: sketch   文件: DiskLruCache.java
private synchronized void completeEdit(Editor editor, boolean success) throws IOException, EditorChangedException, FileNotExistException {
    Entry entry = editor.entry;
    if (entry.currentEditor != editor) {
        throw new EditorChangedException();
    }

    // if this edit is creating the entry for the first time, every index must have a value
    if (success && !entry.readable) {
        for (int i = 0; i < valueCount; i++) {
            if (!entry.getDirtyFile(i).exists()) {
                editor.abort();
                throw new FileNotExistException("edit didn't create file " + i);
            }
        }
    }

    for (int i = 0; i < valueCount; i++) {
        File dirty = entry.getDirtyFile(i);
        if (success) {
            if (dirty.exists()) {
                File clean = entry.getCleanFile(i);
                dirty.renameTo(clean);
                long oldLength = entry.lengths[i];
                long newLength = clean.length();
                entry.lengths[i] = newLength;
                size = size - oldLength + newLength;
            }
        } else {
            deleteIfExists(dirty);
        }
    }

    redundantOpCount++;
    entry.currentEditor = null;
    if (entry.readable | success) {
        entry.readable = true;
        journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
        journalWriter.flush();
        if (success) {
            entry.sequenceNumber = nextSequenceNumber++;
        }
    } else {
        lruEntries.remove(entry.key);
        journalWriter.write(REMOVE + ' ' + entry.key + '\n');
        journalWriter.flush();
    }

    if (size > maxSize || journalRebuildRequired()) {
        executorService.submit(cleanupCallable);
    }
}
 
源代码16 项目: android-discourse   文件: DiskLruCache.java
private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
    Entry entry = editor.entry;
    if (entry.currentEditor != editor) {
        throw new IllegalStateException();
    }

    // If this edit is creating the entry for the first time, every index must have a value.
    if (success && !entry.readable) {
        for (int i = 0; i < valueCount; i++) {
            if (!editor.written[i]) {
                editor.abort();
                throw new IllegalStateException("Newly created entry didn't create value for index " + i);
            }
            if (!entry.getDirtyFile(i).exists()) {
                editor.abort();
                return;
            }
        }
    }

    for (int i = 0; i < valueCount; i++) {
        File dirty = entry.getDirtyFile(i);
        if (success) {
            if (dirty.exists()) {
                File clean = entry.getCleanFile(i);
                dirty.renameTo(clean);
                long oldLength = entry.lengths[i];
                long newLength = clean.length();
                entry.lengths[i] = newLength;
                size = size - oldLength + newLength;
            }
        } else {
            deleteIfExists(dirty);
        }
    }

    redundantOpCount++;
    entry.currentEditor = null;
    if (entry.readable | success) {
        entry.readable = true;
        journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
        if (success) {
            entry.sequenceNumber = nextSequenceNumber++;
        }
    } else {
        lruEntries.remove(entry.key);
        journalWriter.write(REMOVE + ' ' + entry.key + '\n');
    }
    journalWriter.flush();

    if (size > maxSize || journalRebuildRequired()) {
        executorService.submit(cleanupCallable);
    }
}
 
源代码17 项目: olat   文件: FileUtils.java
/**
 * Copy a file from one spot on hard disk to another. Will create any target dirs if necessary.
 * 
 * @param sourceFile
 *            file to copy on local hard disk.
 * @param targetDir
 *            new file to be created on local hard disk.
 * @param move
 * @param filter
 *            file filter or NULL if no filter applied
 * @return true if the copy was successful.
 */
public static boolean copyFileToDir(File sourceFile, File targetDir, boolean move, FileFilter filter, String wt) {
    try {
        // copy only if filter allows. filtered items are considered a success
        // and not a failure of the operation
        if (filter != null && !filter.accept(sourceFile))
            return true;

        // catch if source is directory by accident
        if (sourceFile.isDirectory()) {
            return copyDirToDir(sourceFile, targetDir, move, filter, wt);
        }

        // create target directories
        targetDir.mkdirs(); // don't check for success... would return false on
        // existing dirs
        if (!targetDir.isDirectory())
            return false;
        File targetFile = new File(targetDir, sourceFile.getName());

        // catch move/copy of "same" file -> buggy under Windows.
        if (sourceFile.getCanonicalPath().equals(targetFile.getCanonicalPath()))
            return true;
        if (move) {
            // try to rename it first - operation might only be successful on a local filesystem!
            if (sourceFile.renameTo(targetFile))
                return true;
            // it failed, so continue with copy code!
        }

        bcopy(sourceFile, targetFile, "copyFileToDir:" + wt);

        if (move) {
            // to finish the move accross different filesystems we need to delete the source file
            sourceFile.delete();
        }
    } catch (IOException e) {
        log.error("Could not copy file::" + sourceFile.getAbsolutePath() + " to dir::" + targetDir.getAbsolutePath(), e);
        return false;
    }
    return true;
}
 
源代码18 项目: jdk8u_jdk   文件: FXLauncherTest.java
static void saveFile(String tname, int testcount, File srcFile) {
    File newFile = new File(tname + "-" + testcount + "-" + srcFile.getName());
    System.out.println("renaming " + srcFile.getName() +
                       " to " + newFile.getName());
    srcFile.renameTo(newFile);
}
 
源代码19 项目: openjdk-8   文件: BasicDirectoryModel.java
/**
 * Renames a file in the underlying file system.
 *
 * @param oldFile a <code>File</code> object representing
 *        the existing file
 * @param newFile a <code>File</code> object representing
 *        the desired new file name
 * @return <code>true</code> if rename succeeded,
 *        otherwise <code>false</code>
 * @since 1.4
 */
public boolean renameFile(File oldFile, File newFile) {
    synchronized(fileCache) {
        if (oldFile.renameTo(newFile)) {
            validateFileCache();
            return true;
        }
        return false;
    }
}
 
源代码20 项目: uyuni   文件: RpmRepositoryWriter.java
private void renameSolv(String prefix, Long lastModified) {
    File solv = new File(prefix + SOLV_FILE);

    solv.setLastModified(lastModified);

    solv.renameTo(new File(prefix + "solv"));
}