本文整理汇总了Java中java.io.File.renameTo方法的典型用法代码示例。如果您正苦于以下问题:Java File.renameTo方法的具体用法?Java File.renameTo怎么用?Java File.renameTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.io.File
的用法示例。
在下文中一共展示了File.renameTo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: renameEmbededImages
import java.io.File; //导入方法依赖的package包/类
/**
* 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);
}
示例2: initialize
import java.io.File; //导入方法依赖的package包/类
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();
}
}
示例3: rename
import java.io.File; //导入方法依赖的package包/类
@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;
}
}
示例4: moveOrCopy
import java.io.File; //导入方法依赖的package包/类
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 ;
}
示例5: encrypt
import java.io.File; //导入方法依赖的package包/类
/**
* 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);
}
}
示例6: TopRunnable
import java.io.File; //导入方法依赖的package包/类
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());
}
示例7: save
import java.io.File; //导入方法依赖的package包/类
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);
}
}
示例8: recoverBackup
import java.io.File; //导入方法依赖的package包/类
private static void recoverBackup(File backup, File dest) {
if (backup != null && backup.exists()) {
if (dest.exists())
dest.delete();
backup.renameTo(dest);
}
}
示例9: createFile
import java.io.File; //导入方法依赖的package包/类
/**
* 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");
}
}
}
}
示例10: onPostExecute
import java.io.File; //导入方法依赖的package包/类
@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);
}
}
示例11: renameFileToLayer
import java.io.File; //导入方法依赖的package包/类
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");
}
}
示例12: moveFile
import java.io.File; //导入方法依赖的package包/类
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);
}
示例13: testMoveTreeAfter
import java.io.File; //导入方法依赖的package包/类
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());
}
示例14: move
import java.io.File; //导入方法依赖的package包/类
private static void move(File from, File to) {
if (!from.renameTo(to)) {
Log.w(TAG, "Fail to rename logcat file");
}
}
示例15: performFileTransfer
import java.io.File; //导入方法依赖的package包/类
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;
}