本文整理了Java中java.io.File.renameTo()
方法的一些代码示例,展示了File.renameTo()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。File.renameTo()
方法的具体详情如下:
包路径:java.io.File
类名称:File
方法名:renameTo
[英]Renames this file to newPath. This operation is supported for both files and directories.
Many failures are possible. Some of the more likely failures include:
Note that this method does not throw IOException on failure. Callers must check the return value.
[中]将此文件重命名为newPath。文件和目录都支持此操作。
许多失败是可能的。一些更可能的故障包括:
*在包含源路径和目标路径的目录上需要写入权限。
*两条路径的所有父级都需要搜索权限。
*两条路径必须位于同一装载点上。在Android上,当应用程序试图在内部存储和SD卡之间进行复制时,最有可能达到这一限制。
请注意,此方法不会在失败时引发IOException。调用者必须检查返回值。
代码示例来源:origin: jenkinsci/jenkins
/**
* Called to overwrite
* current version with backup file
*/
@Override
protected void replace(File dst, File backup) throws IOException {
dst.delete(); // any failure up to here is no big deal
if(!backup.renameTo(dst)) {
throw new IOException("Failed to rename "+backup+" to "+dst);
}
}
代码示例来源:origin: square/okhttp
@Override public void rename(File from, File to) throws IOException {
delete(to);
if (!from.renameTo(to)) {
throw new IOException("failed to rename " + from + " to " + to);
}
}
代码示例来源:origin: google/ExoPlayer
private void restoreBackup() {
if (backupName.exists()) {
baseName.delete();
backupName.renameTo(baseName);
}
}
代码示例来源:origin: stackoverflow.com
// File (or directory) with old name
File file = new File("oldname");
// File (or directory) with new name
File file2 = new File("newname");
if (file2.exists())
throw new java.io.IOException("file exists");
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
// File was not successfully renamed
}
代码示例来源:origin: jenkinsci/jenkins
/*package*/ static void relocateOldLogs(File dir) {
final Pattern logfile = Pattern.compile("slave-(.*)\\.log(\\.[0-9]+)?");
File[] logfiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return logfile.matcher(name).matches();
}
});
if (logfiles==null) return;
for (File f : logfiles) {
Matcher m = logfile.matcher(f.getName());
if (m.matches()) {
File newLocation = new File(dir, "logs/slaves/" + m.group(1) + "/slave.log" + Util.fixNull(m.group(2)));
newLocation.getParentFile().mkdirs();
boolean relocationSuccessful=f.renameTo(newLocation);
if (relocationSuccessful) { // The operation will fail if mkdir fails
LOGGER.log(Level.INFO, "Relocated log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
} else {
LOGGER.log(Level.WARNING, "Cannot relocate log file {0} to {1}",new Object[] {f.getPath(),newLocation.getPath()});
}
} else {
assert false;
}
}
}
代码示例来源:origin: airbnb/lottie-android
/**
* If the file created by {@link #writeTempCacheFile(InputStream, FileExtension)} was successfully parsed,
* this should be called to remove the temporary part of its name which will allow it to be a cache hit in the future.
*/
void renameTempFile(FileExtension extension) {
String fileName = filenameForUrl(url, extension, true);
File file = new File(appContext.getCacheDir(), fileName);
String newFileName = file.getAbsolutePath().replace(".temp", "");
File newFile = new File(newFileName);
boolean renamed = file.renameTo(newFile);
L.debug("Copying temp file to real file (" + newFile + ")");
if (!renamed) {
L.warn( "Unable to rename cache file " + file.getAbsolutePath() + " to " + newFile.getAbsolutePath() + ".");
}
}
代码示例来源:origin: geoserver/geoserver
/**
* Backs up a directory <tt>dir</tt> by creating a .bak next to it.
*
* @param dir The directory to back up.
*/
public static void backupDirectory(File dir) throws IOException {
File bak = new File(dir.getCanonicalPath() + ".bak");
if (bak.exists()) {
FileUtils.deleteDirectory(bak);
}
dir.renameTo(bak);
}
代码示例来源:origin: jenkinsci/jenkins
File rootDir = getRootDir();
if (!rootDir.isDirectory()) {
throw new IOException(this + ": " + rootDir + " looks to have already been deleted; siblings: " + Arrays.toString(project.getBuildDir().list()));
File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName());
if (tmp.exists()) {
Util.deleteRecursive(tmp);
boolean renamingSucceeded = rootDir.renameTo(tmp);
Util.deleteRecursive(tmp);
if(tmp.exists())
tmp.deleteOnExit();
throw new IOException(rootDir+" is in use");
LOGGER.log(FINE, "{0}: {1} successfully deleted", new Object[] {this, rootDir});
代码示例来源:origin: apache/storm
public static void unpack(File localrsrc, File dst, boolean symLinksDisabled) throws IOException {
String lowerDst = localrsrc.getName().toLowerCase();
if (lowerDst.endsWith(".jar") ||
lowerDst.endsWith("_jar")) {
unJar(localrsrc, dst);
} else if (lowerDst.endsWith(".zip") ||
lowerDst.endsWith("_zip")) {
unZip(localrsrc, dst);
} else if (lowerDst.endsWith(".tar.gz") ||
lowerDst.endsWith("_tar_gz") ||
lowerDst.endsWith(".tgz") ||
lowerDst.endsWith("_tgz") ||
lowerDst.endsWith(".tar") ||
lowerDst.endsWith("_tar")) {
unTar(localrsrc, dst, symLinksDisabled);
} else {
LOG.warn("Cannot unpack " + localrsrc);
if (!localrsrc.renameTo(dst)) {
throw new IOException("Unable to rename file: [" + localrsrc
+ "] to [" + dst + "]");
}
}
if (localrsrc.isFile()) {
localrsrc.delete();
}
}
代码示例来源:origin: apache/activemq
public static void moveFile(File src, File targetDirectory) throws IOException {
if (!src.renameTo(new File(targetDirectory, src.getName()))) {
// If rename fails we must do a true deep copy instead.
Path sourcePath = src.toPath();
Path targetDirPath = targetDirectory.toPath();
try {
Files.move(sourcePath, targetDirPath.resolve(sourcePath.getFileName()), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
throw new IOException("Failed to move " + src + " to " + targetDirectory + " - " + ex.getMessage());
}
}
}
代码示例来源:origin: spotbugs/spotbugs
public void testFilesMethods() throws IOException {
File f = new File("blah.txt");
File f2 = new File("blah2.txt");
// All of these should generate a warning
f.mkdir();
f.mkdirs();
f.delete();
f.createNewFile();
f.setLastModified(1L);
f.setReadOnly();
f.renameTo(f2);
}
}
代码示例来源:origin: redisson/redisson
private static void doMoveDirectory(File src, File dest) throws IOException {
if (dest.exists()) {
if (!dest.isDirectory()) {
throw new IOException(MSG_NOT_A_DIRECTORY + dest);
}
dest = file(dest, dest.getName());
dest.mkdir();
}
final boolean rename = src.renameTo(dest);
if (!rename) {
doCopyDirectory(src, dest, params());
deleteDir(src);
}
}
代码示例来源:origin: stackoverflow.com
File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"from.txt");
File to = new File(sdcard,"to.txt");
from.renameTo(to);
代码示例来源:origin: SonarSource/sonarqube
private static void moveFile(File sourceFile, File targetFile) {
boolean rename = sourceFile.renameTo(targetFile);
// Check if the file was cached by another process during download
if (!rename && !targetFile.exists()) {
LOGGER.warn("Unable to rename {} to {}", sourceFile.getAbsolutePath(), targetFile.getAbsolutePath());
LOGGER.warn("A copy/delete will be tempted but with no guarantee of atomicity");
try {
Files.move(sourceFile.toPath(), targetFile.toPath());
} catch (IOException e) {
throw new IllegalStateException("Fail to move " + sourceFile.getAbsolutePath() + " to " + targetFile, e);
}
}
}
代码示例来源:origin: jenkinsci/jenkins
/**
* Rename a legacy file to a new name, with care to Windows where {@link File#renameTo(File)}
* doesn't work if the destination already exists.
*/
private void rename(File legacyFile, File newFile) throws IOException {
if (!legacyFile.exists()) return;
if (newFile.exists()) {
Util.deleteFile(newFile);
}
if (!legacyFile.renameTo(newFile)) {
LOGGER.warning("Failed to rename " + legacyFile + " to " + newFile);
}
}
代码示例来源:origin: k9mail/k-9
public static void renameOrMoveByCopying(File from, File to) throws IOException {
deleteFileIfExists(to);
boolean renameFailed = !from.renameTo(to);
if (renameFailed) {
copyFile(from, to);
boolean deleteFromFailed = !from.delete();
if (deleteFromFailed) {
Timber.e("Unable to delete source file after copying to destination!");
}
}
}
代码示例来源:origin: jenkinsci/jenkins
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException {
// JENKINS-16846: if f.getName() is the same as one of the files/directories in f,
// then the rename op will fail
File tmp = new File(f.getAbsolutePath()+".__rename");
if (!f.renameTo(tmp))
throw new IOException("Failed to rename "+f+" to "+tmp);
File t = new File(target.getRemote());
for(File child : reading(tmp).listFiles()) {
File target = new File(t, child.getName());
if(!stating(child).renameTo(creating(target)))
throw new IOException("Failed to rename "+child+" to "+target);
}
deleting(tmp).delete();
return null;
}
}
代码示例来源:origin: guoguibing/librec
public static void renameFile(File file, String regex, String replacement) {
String filename = file.getName();
filename = filename.replaceAll(regex, replacement);
String path = makeDirPath(file.getPath());
file.renameTo(new File(path + filename));
}
代码示例来源:origin: marytts/marytts
private void trimSilences(File wavFile) throws UnsupportedAudioFileException, IOException {
// We hard-code the values here. Use marytts.tools.voiceimport.EndpointDetector if you want to tune them.
int energyBufferLength = 20;
double speechStartLikelihood = 0.1;
double speechEndLikelihood = 0.1;
double shiftFromMinimumEnergyCenter = 0.0;
int numClusters = 4;
double minimumStartSilenceInSeconds = 0.5;
double minimumEndSilenceInSeconds = 0.5;
File tmpFile = new File("tmpAudio.wav");
AudioConverterUtils.removeEndpoints(wavFile.getAbsolutePath(), tmpFile.getAbsolutePath(), energyBufferLength,
speechStartLikelihood, speechEndLikelihood, shiftFromMinimumEnergyCenter, numClusters,
minimumStartSilenceInSeconds, minimumEndSilenceInSeconds);
if (!tmpFile.renameTo(wavFile))
FileUtils.copy(tmpFile.getAbsolutePath(), wavFile.getAbsolutePath());
}
}
代码示例来源:origin: stackoverflow.com
File dir = Environment.getExternalStorageDirectory();
if(dir.exists()){
File from = new File(dir,"from.mp4");
File to = new File(dir,"to.mp4");
if(from.exists())
from.renameTo(to);
}
内容来源于网络,如有侵权,请联系作者删除!