Java Code Examples for java.io.File#renameTo()

The following examples show how to use java.io.File#renameTo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileOperateUtils.java    From sofa-acts with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @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;
    }

}
 
Example 2
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example 3
Source File: LocalFolderImpl.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
*/
  @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?
  }
 
Example 4
Source File: DownloadThread.java    From Alite with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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");
        }
    }
}
 
Example 5
Source File: NativeIO.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
  }
}
 
Example 6
Source File: FileUtil.java    From QSVideoPlayer with Apache License 2.0 5 votes vote down vote up
/**
 * 重命名
 */
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);
}
 
Example 7
Source File: FileBasedCachingEntityCheckerManager.java    From gerbil with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 8
Source File: SVCCallRename.java    From ARMStrong with Mozilla Public License 2.0 5 votes vote down vote up
@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();
	}
}
 
Example 9
Source File: CrashFileManager.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 10
Source File: SQLCipherUtils.java    From cwac-saferoom with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
  }
}
 
Example 11
Source File: GatewayServer.java    From knox with Apache License 2.0 5 votes vote down vote up
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 );
      }
    }
 
Example 12
Source File: FileUtil.java    From star-zone-android with Apache License 2.0 5 votes vote down vote up
/**
 * 先改名,在删除(为了避免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);
    }
}
 
Example 13
Source File: FileUtils.java    From ResearchStack with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 14
Source File: ImageViewerController.java    From MyBox with Apache License 2.0 5 votes vote down vote up
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;
    }

}
 
Example 15
Source File: FileUtils.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 16
Source File: DiskLruCache.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
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);
    }
}
 
Example 17
Source File: FXLauncherTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
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);
}
 
Example 18
Source File: DiskLruCache.java    From sketch with Apache License 2.0 4 votes vote down vote up
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);
    }
}
 
Example 19
Source File: BasicDirectoryModel.java    From openjdk-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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;
    }
}
 
Example 20
Source File: RpmRepositoryWriter.java    From uyuni with GNU General Public License v2.0 3 votes vote down vote up
private void renameSolv(String prefix, Long lastModified) {
    File solv = new File(prefix + SOLV_FILE);

    solv.setLastModified(lastModified);

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