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

The following are Jave code examples for showing how to use renameTo() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: letv   File: QueueFile.java   View Source Code Vote up 6 votes
private static void initialize(File file) throws IOException {
    File tempFile = new File(file.getPath() + ".tmp");
    RandomAccessFile raf = open(tempFile);
    try {
        raf.setLength(PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM);
        raf.seek(0);
        byte[] headerBuffer = new byte[16];
        writeInts(headerBuffer, 4096, 0, 0, 0);
        raf.write(headerBuffer);
        if (!tempFile.renameTo(file)) {
            throw new IOException("Rename failed!");
        }
    } finally {
        raf.close();
    }
}
 
Example 2
Project: marathonv5   File: FileResource.java   View Source Code Vote up 6 votes
@Override public Resource rename(String text) {
    try {
        File sourceFile = path.toFile();
        File destinationFile = path.resolveSibling(text).toFile();
        Path moved;
        if (!sourceFile.getParent().equals(destinationFile.getParent())) {
            moved = Files.move(path, path.resolveSibling(text));
        } else {
            sourceFile.renameTo(destinationFile);
            moved = destinationFile.toPath();
        }
        FileResource to = new FileResource(moved.toFile());
        Event.fireEvent(this, new ResourceModificationEvent(ResourceModificationEvent.MOVED, this, to));
        return to;
    } catch (IOException e) {
        FXUIUtils.showMessageDialog(null, "Unable to rename file: " + e.getMessage(), e.getClass().getName(), AlertType.ERROR);
        return null;
    }
}
 
Example 3
Project: ChronoBike   File: FileSystem.java   View Source Code Vote up 6 votes
public static boolean moveOrCopy(File fileSource, File fileDest)
{
	if(fileSource.exists())
	{
		if(fileDest.exists())
		{
			fileDest.delete();
		}				
		if (!fileSource.renameTo(fileDest))
		{
			boolean ret = copy(fileSource, fileDest);
            fileSource.delete();
            return ret ;
		}
		return true ;
	}
	return false ;
}
 
Example 4
Project: cwac-saferoom   File: SQLCipherUtils.java   View Source Code Vote up 6 votes
/**
 * Replaces this database with a version encrypted with the supplied
 * passphrase, deleting the original. Do not call this while the database
 * is open, which includes during any Room migrations.
 *
 * The passphrase is untouched in this call. If you are going to turn around
 * and use it with SafeHelperFactory.fromUser(), fromUser() will clear the
 * passphrase. If not, please set all bytes of the passphrase to 0 or something
 * to clear out the passphrase.
 *
 * @param ctxt a Context
 * @param originalFile a File pointing to the database
 * @param passphrase the passphrase from the user
 * @throws IOException
 */
public static void encrypt(Context ctxt, File originalFile, char[] passphrase)
  throws IOException {
  SQLiteDatabase.loadLibs(ctxt);

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

    db.rawExecSQL("ATTACH DATABASE '"+newFile.getAbsolutePath()+
      "' AS encrypted KEY '"+String.valueOf(passphrase)+"'");
    db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
    db.rawExecSQL("DETACH DATABASE encrypted");

    int version=db.getVersion();

    db.close();

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

    originalFile.delete();
    newFile.renameTo(originalFile);
  }
}
 
Example 5
Project: Habanero   File: JSONReportMerger.java   View Source Code Vote up 6 votes
/**
 * Give unique names to embedded images to ensure they aren't lost during merge
 * Update report file to reflect new image names
 *
 * @param reportFile
 */
public void renameEmbededImages(File reportFile) throws Throwable {
    File reportDirectory = reportFile.getParentFile();
    Collection<File> embeddedImages = FileUtils.listFiles(reportDirectory, new String[]{reportImageExtension}, true);

    String fileAsString = FileUtils.readFileToString(reportFile);

    for (File image : embeddedImages) {
        String curImageName = image.getName();
        String uniqueImageName = reportDirectory.getName() + "-" + UUID.randomUUID().toString() + "." + reportImageExtension;

        image.renameTo(new File(reportDirectory, uniqueImageName));
        fileAsString = fileAsString.replace(curImageName, uniqueImageName);
    }

    FileUtils.writeStringToFile(reportFile, fileAsString);
}
 
Example 6
Project: csap-core   File: TopRunnable.java   View Source Code Vote up 6 votes
public TopRunnable(int collectionIntervalSeconds) {
	File toprc = new File( System.getenv( "HOME" ) + "/.toprc" );

	if ( toprc.exists() ) {
		logger.error( "Found .toprc file -  CsAgent parses top output for stats collection. File will be renamed" );

		File newName = new File( System.getenv( "HOME" ) + "/OLD.toprc" );

		newName.delete();
		if ( !toprc.renameTo( newName ) ) {
			logger.error( "Failed to rename. This will break service metrics." );
		}
	}

	this.collectionIntervalSeconds = collectionIntervalSeconds;
	command = "top -b -d " + collectionIntervalSeconds;

	commandThread = new Thread( this );
	commandThread.setDaemon( true );
	commandThread.start();
	commandThread.setName( "CsapLinuxTopCommand_" + getCollectionIntervalSeconds() + "s" );
	// commandThread.setPriority(Thread.MAX_PRIORITY) ;
	// logger.info("Spawning Top thread: with priority: "
	// + commandThread.getPriority());
}
 
Example 7
Project: prevent   File: FileUtils.java   View Source Code Vote up 5 votes
public static void save(String path, Set<String> packages) {
    File lock = new File(path + ".lock");
    makeSure(lock);
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(lock));
        for (String key : packages) {
            writer.write(key);
            writer.write("\n");
        }
        writer.close();
        lock.renameTo(new File(path));
    } catch (IOException e) {
        CommonLog.e("cannot save " + path, e);
    }
}
 
Example 8
Project: Logisim   File: Loader.java   View Source Code Vote up 5 votes
private static void recoverBackup(File backup, File dest) {
	if (backup != null && backup.exists()) {
		if (dest.exists())
			dest.delete();
		backup.renameTo(dest);
	}
}
 
Example 9
Project: BaseClient   File: AnvilSaveConverter.java   View Source Code Vote up 5 votes
/**
 * par: filename for the level.dat_mcr backup
 */
private void createFile(String filename)
{
    File file1 = new File(this.savesDirectory, filename);

    if (!file1.exists())
    {
        logger.warn("Unable to create level.dat_mcr backup");
    }
    else
    {
        File file2 = new File(file1, "level.dat");

        if (!file2.exists())
        {
            logger.warn("Unable to create level.dat_mcr backup");
        }
        else
        {
            File file3 = new File(file1, "level.dat_mcr");

            if (!file2.renameTo(file3))
            {
                logger.warn("Unable to create level.dat_mcr backup");
            }
        }
    }
}
 
Example 10
Project: chromium-for-android-56-debug-video   File: OMADownloadHandler.java   View Source Code Vote up 5 votes
@Override
protected void onPostExecute(Boolean success) {
    DownloadManager manager =
            (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    if (success) {
        String path = mDownloadInfo.getFilePath();
        if (!TextUtils.isEmpty(path)) {
            // Move the downloaded content from the app directory to public directory.
            File fromFile = new File(path);
            String fileName = fromFile.getName();
            File toFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS), fileName);
            if (fromFile.renameTo(toFile)) {
                manager.addCompletedDownload(
                        fileName, mDownloadInfo.getDescription(), false,
                        mDownloadInfo.getMimeType(), toFile.getPath(),
                        mDownloadInfo.getContentLength(), true);
            } else if (fromFile.delete()) {
                Log.w(TAG, "Failed to rename the file.");
                return;
            } else {
                Log.w(TAG, "Failed to rename and delete the file.");
            }
        }
        showNextUrlDialog(mOMAInfo);
    } else if (mDownloadId != DownloadItem.INVALID_DOWNLOAD_ID) {
        // Remove the downloaded content.
        manager.remove(mDownloadId);
    }
}
 
Example 11
Project: geomapapp   File: FilesUtil.java   View Source Code Vote up 5 votes
public static void renameFileToLayer(String tempName) throws IOException{
	//Creates layers directory if one does not exists
	File layerDir = new File(gmaRoot + File.separator + "layers");
	File tempFile = new File(layerDir + File.separator + tempName);
	File origFile = new File(layerDir + File.separator + "MySessions.xml");
	if( tempFile.exists() ) {
		if (!origFile.delete()) {
			System.out.println("Could not delete file");
		return;
		}
		//Rename the new file to the filename the original file had.
		if (!tempFile.renameTo(origFile))
		System.out.println("Could not rename files");
	}
}
 
Example 12
Project: Accessibility   File: FileUtils.java   View Source Code Vote up 5 votes
public static boolean moveFile(String srcFileName, String destFileName) {
    File srcFile = new File(srcFileName);
    if (!srcFile.exists() || !srcFile.isFile())
        return false;

    File destFile = new File(destFileName);
    if (!destFile.getParentFile().exists())
        destFile.getParentFile().mkdirs();

    return srcFile.renameTo(destFile);
}
 
Example 13
Project: incubator-netbeans   File: RenameTest.java   View Source Code Vote up 4 votes
public void testMoveTreeAfter () throws Exception {
    File folder = new File(workDir, "folder");
    folder.mkdirs();
    File file1 = new File(folder, "file1");
    write(file1, "file1 content");
    File file2 = new File(folder, "file2");
    write(file2, "file2 content");
    File subFolder1 = new File(folder, "folder1");
    subFolder1.mkdirs();
    File file11 = new File(subFolder1, "file");
    write(file11, "file11 content");
    File subFolder2 = new File(folder, "folder2");
    subFolder2.mkdirs();
    File file21 = new File(subFolder2, "file");
    write(file21, "file21 content");

    File target = new File(workDir, "target");
    File moved1 = new File(target, file1.getName());
    File moved2 = new File(target, file2.getName());
    File moved11 = new File(new File(target, file11.getParentFile().getName()), file11.getName());
    File moved21 = new File(new File(target, file21.getParentFile().getName()), file21.getName());

    add(file1, file11, file21);
    commit(file1, file11);

    folder.renameTo(target);
    GitClient client = getClient(workDir);
    Monitor m = new Monitor();
    client.addNotificationListener(m);
    client.rename(folder, target, true, m);
    assertTrue(moved1.exists());
    assertTrue(moved2.exists());
    assertTrue(moved11.exists());
    assertTrue(moved21.exists());
    assertEquals(new HashSet<File>(Arrays.asList(moved1, moved11, moved21)), m.notifiedFiles);
    Map<File, GitStatus> statuses = client.getStatus(new File[] { file1, file2, file11, file21, moved1, moved11, moved2, moved21 }, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, file1, true, GitStatus.Status.STATUS_REMOVED, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_REMOVED, false);
    assertNull(statuses.get(file2));
    assertStatus(statuses, workDir, file11, true, GitStatus.Status.STATUS_REMOVED, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_REMOVED, false);
    assertNull(statuses.get(file21));
    assertStatus(statuses, workDir, moved1, true, GitStatus.Status.STATUS_ADDED, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_ADDED, false);
    assertStatus(statuses, workDir, moved2, false, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_ADDED, GitStatus.Status.STATUS_ADDED, false);
    assertStatus(statuses, workDir, moved11, true, GitStatus.Status.STATUS_ADDED, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_ADDED, false);
    assertStatus(statuses, workDir, moved21, true, GitStatus.Status.STATUS_ADDED, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_ADDED, false);
    assertTrue(statuses.get(moved1).isRenamed());
    assertTrue(statuses.get(moved11).isRenamed());
    // file21 was not committed
    assertFalse(statuses.get(moved21).isRenamed());
}
 
Example 14
Project: chromium-for-android-56-debug-video   File: LogcatExtractionCallable.java   View Source Code Vote up 4 votes
private static void move(File from, File to) {
    if (!from.renameTo(to)) {
        Log.w(TAG, "Fail to rename logcat file");
    }
}
 
Example 15
Project: SmartMath   File: MFPFileManagerActivity.java   View Source Code Vote up 4 votes
public boolean performFileTransfer(File fSrc, File fDest, String strAction)	{
	// here, always assume that fSrc and fDest are valid files.
	boolean bFileOperationResult = false;
	if (strAction.trim().compareToIgnoreCase("cut") == 0)	{
		// cut - paste:
		boolean bFileOperationResult1 = false, bFileOperationResult2 = false;
		bFileOperationResult1 = copyFileOrFolder(fSrc, fDest);
		if (bFileOperationResult1)	{	// only if copy is successful, we try to delete.
			bFileOperationResult2 = deleteFileOrFolder(fSrc);
			// only if delete is successful, we prevent original file from being copied.
			if (bFileOperationResult2)	{
				mmfpClipboardFileType = null;	// after a successful cut-paste, the original file no longer exists
				bFileOperationResult = true;
			}
		}
	} else if (strAction.trim().compareToIgnoreCase("copy") == 0)	{
		// copy - paste
		bFileOperationResult = copyFileOrFolder(fSrc, fDest);
  		} else if (strAction.trim().compareToIgnoreCase("rename") == 0)	{
  			// rename:
   		/*
   		 * note that if destination is a non-empty folder, rename will
   		 * fail (return false). In other words, destination must be either
   		 * a file or an empty folder. If destination has some defined
   		 * functions, these functions will be removed from memory and source's
   		 * function will replace them. And the original source's functions
   		 * will be removed as well.
   		 */
  			if (fDest.exists())	{
    		MFPAdapter.unloadFileOrFolder(fDest.getAbsolutePath());
  			}
  			bFileOperationResult = fSrc.renameTo(fDest);
		if (bFileOperationResult)	{
    		MFPAdapter.unloadFileOrFolder(fSrc.getAbsolutePath());
		}
		if (fDest.exists())	{
			// whether successful or not, we have to load dest coz we unload it b4 rename.
			MFPAdapter.loadFileOrFolder(fDest.getAbsolutePath(), null);
		}
  		} else	{
  			bFileOperationResult = false;	// invalid action
  		}
	setAdapter(INT_INVALID_POSITION);
	return bFileOperationResult;
}
 
Example 16
Project: HDImageView   File: DiskLruCache.java   View Source Code Vote up 4 votes
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 (!entry.getDirtyFile(i).exists()) {
                editor.abort();
                throw new IllegalStateException("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');
        if (success) {
            entry.sequenceNumber = nextSequenceNumber++;
        }
    } else {
        lruEntries.remove(entry.key);
        journalWriter.write(REMOVE + ' ' + entry.key + '\n');
    }

    if (size > maxSize || journalRebuildRequired()) {
        executorService.submit(cleanupCallable);
    }
}
 
Example 17
Project: ColorMOTD   File: BukkitMain.java   View Source Code Vote up 4 votes
public BukkitMotdConfig loadConfig() {
    saveDefaultConfig();
    reloadConfig();
    FileConfiguration config = getConfig();

    // check for ColorMOTD 1.x
    if (!config.contains("version")) {
        logger.info("ColorMOTD 1.x detected, renaming 'config.yml' to 'config.old.yml' ...");

        File oldLocation = new File(getDataFolder(), "config.yml");
        File newLocation = new File(getDataFolder(), "config.old.yml");
        newLocation.delete();
        if (!oldLocation.renameTo(newLocation)) {
            throw new RuntimeException("Unable to rename 'config.yml' to 'config.old.yml'!");
        }
        saveDefaultConfig();
        reloadConfig();
    }

    BukkitMotdConfig r = new BukkitMotdConfig();

    for (Object motdObj : config.getList("motds")) {
        if (motdObj instanceof String) {
            r.addMotd(((String) motdObj).replace("\\n", "\n"));
        } else if (motdObj instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) motdObj;
            String line1 = map.getOrDefault("line1", "").toString();
            String line2 = map.get("line2").toString();
            r.addMotd(line1 + (line2 == null ? "" : "\n" + line2));
        } else {
            throw new RuntimeException("Unknown motd type: " + motdObj.getClass().getCanonicalName());
        }
    }

    File iconFolder = new File(getDataFolder(), "favicons/");
    if(!iconFolder.isDirectory()) iconFolder.mkdirs();
    //noinspection ConstantConditions
    for(File file : iconFolder.listFiles((dir, name) ->
            SUPPORTED_IMAGE_FORMAT.stream().anyMatch(name::endsWith))) {
        try {
            BufferedImage image = ImageIO.read(file);
            r.addServerIcon(new BukkitMotdServerIcon(image));
        } catch (IOException e) {
            throw new UncheckedIOException("Unable to load " + file.getName(), e);
        }
    }

    return r;
}
 
Example 18
Project: flume-release-1.7.0   File: DurablePositionTracker.java   View Source Code Vote up 4 votes
/**
 * If the file exists at startup, then read it, roll it, and open a new one.
 * We go through this to avoid issues with partial reads at the end of the
 * file from a previous crash. If we append to a bad record,
 * our writes may never be visible.
 * @param trackerFile
 * @param target
 * @return
 * @throws IOException
 */
public static DurablePositionTracker getInstance(File trackerFile,
    String target) throws IOException {

  if (!trackerFile.exists()) {
    return new DurablePositionTracker(trackerFile, target);
  }

  // exists
  DurablePositionTracker oldTracker =
      new DurablePositionTracker(trackerFile, target);
  String existingTarget = oldTracker.getTarget();
  long targetPosition = oldTracker.getPosition();
  oldTracker.close();

  File tmpMeta = File.createTempFile(trackerFile.getName(), ".tmp",
      trackerFile.getParentFile());
  tmpMeta.delete();
  DurablePositionTracker tmpTracker =
      new DurablePositionTracker(tmpMeta, existingTarget);
  tmpTracker.storePosition(targetPosition);
  tmpTracker.close();

  // On windows, things get messy with renames...
  // FIXME: This is not atomic. Consider implementing a recovery procedure
  // so that if it does not exist at startup, check for a rolled version
  // before creating a new file from scratch.
  if (PlatformDetect.isWindows()) {
    if (!trackerFile.delete()) {
      throw new IOException("Unable to delete existing meta file " +
          trackerFile);
    }
  }

  // rename tmp file to meta
  if (!tmpMeta.renameTo(trackerFile)) {
    throw new IOException("Unable to rename " + tmpMeta + " to " +
        trackerFile);
  }

  // return a new known-good version that is open for append
  DurablePositionTracker newTracker =
      new DurablePositionTracker(trackerFile, existingTarget);
  return newTracker;
}
 
Example 19
Project: OpenDiabetes   File: Preprocessor.java   View Source Code Vote up 4 votes
/**
 * Preprocesses a single file. <p>
 *
 * @param sourceDir under which the input file is located
 * @param targetDir under which the output file is to be written
 * @param fileName to be preprocessed
 * @param altExt to use for output file name
 * @param encoding with which to write output file
 * @param options used to control preprocessing
 * @param defines CSV list of symbol definition expressions
 * @param resolver with which to perform property and path expansions
 * @throws PreprocessorException if an error occurs while loading,
 *      preprocessing or saving the result of preprocessing the
 *      specified input file
 */
public static void preprocessFile(File sourceDir, File targetDir,
        String fileName, String altExt, String encoding, int options,
        String defines, IResolver resolver) throws PreprocessorException {

    String       sourcePath   = translatePath(sourceDir, fileName, null);
    String       targetPath   = translatePath(targetDir, fileName, altExt);
    File         targetFile   = new File(targetPath);
    File         backupFile   = new File(targetPath + "~");
    boolean      sameDir      = sourceDir.equals(targetDir);
    boolean      sameExt      = (altExt ==  null);
    boolean      verbose      = Option.isVerbose(options);
    boolean      testOnly     = Option.isTestOnly(options);
    boolean      backup       = Option.isBackup(options);
    Preprocessor preprocessor = new Preprocessor(sourcePath,
            encoding, options, resolver, defines);

    if (verbose) {
        log("Reading \"" + sourcePath + "\"");
    }

    preprocessor.loadDocument();

    boolean modified = preprocessor.preprocess();
    boolean rewrite  = modified || !sameDir || !sameExt;

    if (!rewrite) {
        if (verbose) {
            log(fileName + " ... not modified");
        }

        return;
    } else if (verbose) {
        log(fileName + " ... modified");
    }

    if (testOnly) {
        return;
    }

    try {
        targetFile.getParentFile().mkdirs();
    } catch (Exception e) {
        throw new PreprocessorException("mkdirs failed \"" + targetFile
                + "\": " + e); // NOI18N
    }

    backupFile.delete();

    if (targetFile.exists() && !targetFile.renameTo(backupFile)) {
        throw new PreprocessorException("Rename failed: \""
                + targetFile
                + "\" => \""
                + backupFile
                +"\"" ); // NOI18N
    }

    if (verbose) {
        log("Writing \"" + targetPath + "\"");
    }

    preprocessor.saveDocument(targetPath);

    if (!backup) {
        backupFile.delete();
    }
}
 
Example 20
Project: OpenJSharp   File: BasicDirectoryModel.java   View Source Code Vote up 3 votes
/**
 * 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;
    }
}