java.nio.file.Files.move()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(9.4k)|赞(0)|评价(0)|浏览(720)

本文整理了Java中java.nio.file.Files.move()方法的一些代码示例,展示了Files.move()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Files.move()方法的具体详情如下:
包路径:java.nio.file.Files
类名称:Files
方法名:move

Files.move介绍

暂无

代码示例

代码示例来源:origin: neo4j/neo4j

@Override
public void renameFile( File from, File to, CopyOption... copyOptions ) throws IOException
{
  Files.move( from.toPath(), to.toPath(), copyOptions );
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Tries to move/rename a file from one path to another.
 * Uses {@link java.nio.file.Files#move} when available.
 * Does not use {@link java.nio.file.StandardCopyOption#REPLACE_EXISTING} or any other options.
 * TODO candidate for moving to {@link Util}
 */
static void move(File src, File dest) throws IOException {
  try {
    Files.move(src.toPath(), dest.toPath());
  } catch (IOException x) {
    throw x;
  } catch (Exception x) {
    throw new IOException(x);
  }
}

代码示例来源:origin: neo4j/neo4j

public static void renameFile( File srcFile, File renameToFile, CopyOption... copyOptions ) throws IOException
{
  Files.move( srcFile.toPath(), renameToFile.toPath(), copyOptions );
}

代码示例来源:origin: jenkinsci/jenkins

private void addEmptyUsernameIfExists(Map<String, File> users) throws IOException {
  File emptyUsernameConfigFile = new File(usersDirectory, User.CONFIG_XML);
  if (emptyUsernameConfigFile.exists()) {
    File newEmptyUsernameDirectory = new File(usersDirectory, EMPTY_USERNAME_DIRECTORY_NAME);
    Files.createDirectory(newEmptyUsernameDirectory.toPath());
    File newEmptyUsernameConfigFile = new File(newEmptyUsernameDirectory, User.CONFIG_XML);
    Files.move(emptyUsernameConfigFile.toPath(), newEmptyUsernameConfigFile.toPath());
    users.put("", newEmptyUsernameDirectory);
  }
}

代码示例来源:origin: stackoverflow.com

long bytes = java.nio.file.Files.move( 
        new java.io.File("<filepath1>").toPath(), 
        new java.io.File("<filepath2>").toPath(),
        java.nio.file.StandardCopyOption.ATOMIC_MOVE,
        java.nio.file.StandardCopyOption.REPLACE_EXISTING);

代码示例来源:origin: apache/storm

@Override
public void commit() throws IOException {
  if (!isTmp()) {
    throw new IllegalStateException("Can only write to a temporary part file.");
  }
  File dest = new File(_path.getParentFile(), BlobStoreFile.BLOBSTORE_DATA_FILE);
  if (_mustBeNew) {
    Files.move(_path.toPath(), dest.toPath(), StandardCopyOption.ATOMIC_MOVE);
  } else {
    Files.move(_path.toPath(), dest.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
  }
}

代码示例来源:origin: jenkinsci/jenkins

void migrateUsers(UserIdMapper mapper) throws IOException {
  LOGGER.fine("Beginning migration of users to userId mapping.");
  Map<String, File> existingUsers = scanExistingUsers();
  for (Map.Entry<String, File> existingUser : existingUsers.entrySet()) {
    File newDirectory = mapper.putIfAbsent(existingUser.getKey(), false);
    LOGGER.log(Level.INFO, "Migrating user '" + existingUser.getKey() + "' from 'users/" + existingUser.getValue().getName() + "/' to 'users/" + newDirectory.getName() + "/'");
    Files.move(existingUser.getValue().toPath(), newDirectory.toPath(), StandardCopyOption.REPLACE_EXISTING);
  }
  mapper.save();
  LOGGER.fine("Completed migration of users to userId mapping.");
}

代码示例来源:origin: alibaba/jstorm

@Override
public void commit() throws IOException {
  if (!isTmp()) {
    throw new IllegalStateException("Can only write to a temporary part file.");
  }
  File dest = new File(_path.getParentFile(), BlobStoreFile.BLOBSTORE_DATA_FILE);
  if (_mustBeNew) {
    Files.move(_path.toPath(), dest.toPath(), StandardCopyOption.ATOMIC_MOVE);
  } else {
    Files.move(_path.toPath(), dest.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
  }
}

代码示例来源:origin: apache/storm

/**
 * Move fromDir to toDir, and try to make it an atomic move if possible
 *
 * @param fromDir what to move
 * @param toDir   where to move it from
 * @throws IOException on any error
 */
public void moveDirectoryPreferAtomic(File fromDir, File toDir) throws IOException {
  FileUtils.forceMkdir(toDir);
  Files.move(fromDir.toPath(), toDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
}

代码示例来源:origin: apache/geode

private void backupFile(Path targetDir, File file) throws IOException {
 Files.move(file.toPath(), targetDir.resolve(file.getName()));
}

代码示例来源:origin: apache/nifi

protected void move(final File source, final File target, final boolean overwrite) throws IOException {
  final File targetDirectory = target.getParentFile();
  // convert to path and use Files.move instead of file.renameTo so that if we fail, we know why
  final Path targetPath = target.toPath();
  if (!targetDirectory.exists()) {
    Files.createDirectories(targetDirectory.toPath());
  }
  final CopyOption[] copyOptions = overwrite ? new CopyOption[] {StandardCopyOption.REPLACE_EXISTING} : new CopyOption[] {};
  Files.move(source.toPath(), targetPath, copyOptions);
}

代码示例来源: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: BroadleafCommerce/BroadleafCommerce

@Override
public void replaceExisting(File src, File dest) throws IOException {
  synchronized (getFileMoveLock(dest)) {
    if (src.exists()) {
      try {
        Files.move(src.toPath(), dest.toPath(), ATOMIC_MOVE, REPLACE_EXISTING);
      } catch (AtomicMoveNotSupportedException e) {
        Files.move(src.toPath(), dest.toPath(), REPLACE_EXISTING);
      }
    }
  }
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

protected void replaceExisting(File src, File dest) throws IOException {
  synchronized (getFileMoveLock(dest)) {
    if (src.exists()) {
      try {
        Files.move(src.toPath(), dest.toPath(), ATOMIC_MOVE, REPLACE_EXISTING);
      } catch (AtomicMoveNotSupportedException e) {
        Files.move(src.toPath(), dest.toPath(), REPLACE_EXISTING);
      }
    }
  }
}

代码示例来源: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: apache/flink

@Override
public boolean rename(final Path src, final Path dst) throws IOException {
  final File srcFile = pathToFile(src);
  final File dstFile = pathToFile(dst);
  final File dstParent = dstFile.getParentFile();
  // Files.move fails if the destination directory doesn't exist
  //noinspection ResultOfMethodCallIgnored -- we don't care if the directory existed or was created
  dstParent.mkdirs();
  try {
    Files.move(srcFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    return true;
  }
  catch (NoSuchFileException | AccessDeniedException | DirectoryNotEmptyException | SecurityException ex) {
    // catch the errors that are regular "move failed" exceptions and return false
    return false;
  }
}

代码示例来源:origin: eclipse-vertx/vert.x

public Void perform() {
  try {
   Path source = vertx.resolveFile(from).toPath();
   Path target = vertx.resolveFile(to).toPath();
   Files.move(source, target, copyOptions);
  } catch (IOException e) {
   throw new FileSystemException(e);
  }
  return null;
 }
};

代码示例来源:origin: wildfly/wildfly

/**
 * Moves file to file.1, file.1 to file.2 etc. Removes file.{maxBackupIndex}
 */
private void rotate(final File file) throws IOException {
  closeStreams();
  final String suffix = dateTimeFormatter != null ? dateTimeFormatter.format(ZonedDateTime.now(clock)) : "";
  final Path fileWithSuffix = Paths.get(file.getAbsolutePath() + suffix);
  Files.deleteIfExists(Paths.get(fileWithSuffix + "." + maxBackupIndex));
  for (int i = maxBackupIndex - 1; i >= 1; i--) {
    final Path src = Paths.get(fileWithSuffix + "." + i);
    if (Files.exists(src)) {
      final Path target = Paths.get(fileWithSuffix + "." + (i + 1));
      Files.move(src, target, StandardCopyOption.REPLACE_EXISTING);
    }
  }
  Files.move(file.toPath(), Paths.get(fileWithSuffix + ".1"), StandardCopyOption.REPLACE_EXISTING);
  setFile(file);
}

代码示例来源:origin: apache/nifi

@Override
  public String changePartitionName(final String swapLocation, final String newPartitionName) throws IOException {
    final File existingFile = new File(swapLocation);
    if (!existingFile.exists()) {
      throw new FileNotFoundException("Could not change name of partition for swap location " + swapLocation + " because no swap file exists at that location");
    }

    final String existingFilename = existingFile.getName();

    final String newFilename;
    final int dotIndex = existingFilename.indexOf(".");
    if (dotIndex < 0) {
      newFilename = existingFilename + "." + newPartitionName + ".swap";
    } else {
      newFilename = existingFilename.substring(0, dotIndex) + "." + newPartitionName + ".swap";
    }

    final File newFile = new File(existingFile.getParentFile(), newFilename);
    // Use Files.move and convert to Path's instead of File.rename so that we get an IOException on failure that describes why we failed.
    Files.move(existingFile.toPath(), newFile.toPath());

    return newFile.getAbsolutePath();
  }
}

代码示例来源:origin: apache/drill

@Override
 public void action(URL url) {
  String fileName = url.getFile();
  File file = new File(url.getPath());
  String currentDateTime = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
  String newFileName = new StringBuilder(fileName)
    .insert(fileName.lastIndexOf("."), "-" + currentDateTime)
    .toString();
  Path filePath = file.toPath();
  try {
   Files.move(filePath, filePath.resolveSibling(newFileName));
  } catch (IOException e) {
   logger.error("There was an error during file {} rename.", fileName, e);
  }
 }
},

相关文章

微信公众号

最新文章

更多