com.google.common.io.Files#move ( )源码实例Demo

下面列出了com.google.common.io.Files#move ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * Saves a model (as a {@link Generation} to a given file.
 *
 * @see #readModel()
 */
private static void saveModel(Generation generation, File modelFile) throws IOException {

  File newModelFile = File.createTempFile(DelegateGenerationManager.class.getSimpleName(), ".bin.gz");
  log.info("Writing model to {}", newModelFile);

  try {
    GenerationSerializer.writeGeneration(generation, newModelFile);
  } catch (IOException ioe) {
    if (newModelFile.exists() && !newModelFile.delete()) {
      log.warn("Could not delete {}", newModelFile);
    }
    throw ioe;
  }

  log.info("Done, moving into place at {}", modelFile);
  if (modelFile.exists() && !modelFile.delete()) {
    log.warn("Could not delete old {}", modelFile);
  }
  Files.move(newModelFile, modelFile);
}
 
源代码2 项目: STGUploader   文件: FileGetter.java
public static void migrateFiles(){
    File oldDir = new File(Environment.getExternalStorageDirectory(), "STG");
    if(oldDir.exists()) {
        File[] files = oldDir.listFiles();
        for(File file : files) {
            File newFile = getFile(file.getName());
            try {
                Files.move(file, newFile);
            } catch (IOException e) {
                e.printStackTrace();
                Logger.error(e.toString());
            }
        }
        oldDir.delete();
    }
}
 
private synchronized void closeAppender() throws IOException {
  if (appender != null) {
    try {
      appender.close(); // Want to know of output stream close failed -- maybe failed to write
    } catch (IOException ioe) {
      // But proceed anyway with what was written
      log.warn("Failed to close appender cleanly", ioe);
    }
    if (appendFile.exists()) {
      if (IOUtils.isGZIPFileEmpty(appendFile)) {
        log.info("File appears to have no data, deleting: {}", appendFile);
        if (!appendFile.delete()) {
          log.warn("Could not delete {}", appendFile);
        }
      } else {
        Files.move(appendFile, new File(inputDir, System.currentTimeMillis() + ".csv.gz"));
      }
    }
  }
}
 
源代码4 项目: science-journal   文件: SimpleMetaDataManager.java
@Override
public void moveExperimentToAnotherAccount(Experiment experiment, AppAccount targetAccount)
    throws IOException {
  // Move experiment directory.
  File sourceExperimentDirectory =
      FileMetadataUtil.getInstance()
          .getExperimentDirectory(appAccount, experiment.getExperimentId());
  File targetExperimentDirectory =
      FileMetadataUtil.getInstance()
          .getExperimentDirectory(targetAccount, experiment.getExperimentId());
  File parent = targetExperimentDirectory.getParentFile();
  if (!parent.exists() && !parent.mkdir()) {
    if (Log.isLoggable(TAG, Log.ERROR)) {
      Log.e(TAG, "Failed to create parent directory.");
    }
    // TODO(lizlooney): Handle this situation!
    throw new IOException("Failed to create parent directory " + parent);
  }
  Files.move(sourceExperimentDirectory, targetExperimentDirectory);
}
 
源代码5 项目: datamill   文件: CommandLineSteps.java
@When("^" + Phrases.SUBJECT + " moves \"(.+)\" to \"(.+)\" in the temporary directory$")
public void move(String from, String to) throws IOException {
    File temporaryDirectory = (File) propertyStore.get(TEMPORARY_DIRECTORY);
    if (temporaryDirectory == null || !temporaryDirectory.isDirectory()) {
        fail("A temporary directory was not created to move files!");
    }

    String resolvedFrom = placeholderResolver.resolve(from);
    String resolvedTo = placeholderResolver.resolve(to);

    File fromFile = new File(temporaryDirectory, resolvedFrom);
    File toFile = new File(temporaryDirectory, resolvedTo);

    if (fromFile.exists()) {
        Files.move(fromFile, toFile);
    } else {
        fail("Failed to move non-existent file " + fromFile.getAbsolutePath());
    }
}
 
源代码6 项目: PeerWasp   文件: Move.java
private void moveManyFilesIntoFolder(List<Path> files, Path dstFolder, int nrMoves) {
	ArrayList<Path> movedFiles = new ArrayList<Path>();

	for(int i = 0; i < nrMoves; i++){
		if(files.get(i).toFile().isDirectory()){
			nrMoves--;
			continue;
		}

		Path dstPath = dstFolder.resolve(files.get(i).getFileName());
		try {
			Files.move(files.get(i).toFile(), dstPath.toFile());
			movedFiles.add(dstPath);
		} catch (IOException e) {
			e.printStackTrace();
			movedFiles.remove(dstPath);
		}
	}

	assertTrue(nrMoves == movedFiles.size());
	waitForExists(movedFiles, WAIT_TIME_LONG);
}
 
源代码7 项目: glowroot   文件: WebDriverSetup.java
private static void downloadAndExtractGeckoDriver(File directory, String downloadFilenameSuffix,
        String downloadFilenameExt, String optionalExt, Archiver archiver) throws IOException {
    // using System.out to make sure user sees why there is a delay here
    System.out.print("Downloading Mozilla geckodriver " + GECKO_DRIVER_VERSION + "...");
    URL url = new URL("https://github.com/mozilla/geckodriver/releases/download/v"
            + GECKO_DRIVER_VERSION + "/geckodriver-v" + GECKO_DRIVER_VERSION + '-'
            + downloadFilenameSuffix + '.' + downloadFilenameExt);
    InputStream in = url.openStream();
    File archiveFile = File.createTempFile("geckodriver-" + GECKO_DRIVER_VERSION + '-',
            '.' + downloadFilenameExt);
    Files.asByteSink(archiveFile).writeFrom(in);
    in.close();
    archiver.extract(archiveFile, directory);
    Files.move(new File(directory, "geckodriver" + optionalExt),
            new File(directory, "geckodriver-" + GECKO_DRIVER_VERSION + optionalExt));
    archiveFile.delete();
    System.out.println(" OK");
}
 
源代码8 项目: PeerWasp   文件: EnhancedMove.java
private void manyNonEmptyFolderMoveTestFunc() throws IOException{
		logger.debug("--------------------START------------");
		int nrFolders = 10;
		int nrFilesPerFolder = 10;
		Path destination = addFolder();
		List<Path> paths = addManyFilesInManyFolders(10, 10);
		List<Path> destinationPaths = new ArrayList<Path>();
		int totalFiles = nrFolders + nrFolders * nrFilesPerFolder + 1;

		assertCleanedUpState(totalFiles);
		Path lastDestination = null;
		for(Path path: paths){
			if(path.toFile().isDirectory()){
				lastDestination = destination.resolve(path.getFileName());
//				destinationPaths.add(lastDestination);
				if(path.toFile().exists()){
					Files.move(path.toFile(), lastDestination.toFile());
					destinationPaths.add(lastDestination);
				}
			}

		}
		waitForExists(destinationPaths, WAIT_TIME_SHORT);
		assertCleanedUpState(totalFiles);
		logger.debug("--------------------END------------");
	}
 
源代码9 项目: PeerWasp   文件: Move.java
@Test
public void localUpdateOnLocalMoveTest() throws IOException{
	Path folder = addFolder();
	Path srcFile = addFile();
	Path dstFile = folder.resolve(srcFile.getFileName());
	Files.move(srcFile.toFile(), dstFile.toFile());
	sleepMillis(config.getAggregationIntervalInMillis() / 2);
	updateSingleFile(dstFile, true);
	assertCleanedUpState(2);
}
 
@Override
public void moveFile(File from, File to) {
    try {
        Files.move(from, to);
    } catch (IOException e) {
        throw new InitializerException("It was not possible to move file from {} to {}",e, from, to);
    }
}
 
源代码11 项目: bazel   文件: LegacyDynamicSpawnStrategy.java
private void moveFileOutErr(ActionExecutionContext actionExecutionContext, FileOutErr outErr)
    throws IOException {
  if (outErr.getOutputPath().exists()) {
    Files.move(
        outErr.getOutputPath().getPathFile(),
        actionExecutionContext.getFileOutErr().getOutputPath().getPathFile());
  }
  if (outErr.getErrorPath().exists()) {
    Files.move(
        outErr.getErrorPath().getPathFile(),
        actionExecutionContext.getFileOutErr().getErrorPath().getPathFile());
  }
}
 
源代码12 项目: mmtf-spark   文件: DatasetFileConverter.java
private static void moveToSingleFile(String dirname, String filename) throws IOException {
    File part = getPartsFile(dirname);
    if (part != null) {
        File singleFile = new File(filename);
        Files.move(part, singleFile);
        FileUtils.deleteDirectory(new File(dirname));
    }
}
 
源代码13 项目: kafka-connect-spooldir   文件: InputFile.java
public void moveToDirectory(File outputDirectory) {
  File outputFile = new File(outputDirectory, this.inputFile.getName());
  try {
    if (this.inputFile.exists()) {
      log.info("Moving {} to {}", this.inputFile, outputFile);
      Files.move(this.inputFile, outputFile);
    }
  } catch (IOException e) {
    log.error("Exception thrown while trying to move {} to {}", this.inputFile, outputFile, e);
  }
}
 
源代码14 项目: science-journal   文件: SimpleMetaDataManager.java
@Override
public void moveAllExperimentsToAnotherAccount(AppAccount targetAccount) throws IOException {
  // This method should not be called if canMoveAllExperimentsToAnotherAccount returns false.
  if (!canMoveAllExperimentsToAnotherAccount(targetAccount)) {
    throw new IllegalStateException("moveAllExperimentsToAnotherAccount now allowed now");
  }

  getFileMetadataManager().beforeMovingAllExperimentsToAnotherAccount();

  // Move experiment root directory.
  File sourceExperimentsRoot =
      FileMetadataUtil.getInstance().getExperimentsRootDirectory(appAccount);
  File targetExperimentsRoot =
      FileMetadataUtil.getInstance().getExperimentsRootDirectory(targetAccount);
  Files.move(sourceExperimentsRoot, targetExperimentsRoot);

  // Move user_metadata.proto.
  File sourceUserMetadataFile = FileMetadataUtil.getInstance().getUserMetadataFile(appAccount);
  File targetUserMetadataFile = FileMetadataUtil.getInstance().getUserMetadataFile(targetAccount);
  Files.move(sourceUserMetadataFile, targetUserMetadataFile);

  // Move experiment and sensor databases.
  ImmutableList<String> filesToMove =
      ImmutableList.of("main.db", "main.db-journal", "sensors.db", "sensors.db-journal");
  String[] sourceNames = context.databaseList();
  for (String sourceName : sourceNames) {
    if (filesToMove.contains(sourceName)) {
      File sourceFile = context.getDatabasePath(sourceName);
      String targetName = targetAccount.getDatabaseFileName(sourceName);
      File targetFile = new File(sourceFile.getParentFile(), targetName);
      Files.move(sourceFile, targetFile);
    }
  }
}
 
源代码15 项目: mojito   文件: DropXliffImportCommandTest.java
void removeDateFromXliffNames() throws IOException {
    Collection<File> files = FileUtils.listFiles(getTargetTestDir(), null, true);
    for (File file : files) {
        String newName = file.getName().replaceAll("_.*.xliff", "_.xliff");
        Files.move(file, file.toPath().resolveSibling(newName).toFile());
    }
}
 
源代码16 项目: eclipse.jdt.ls   文件: WorkspaceEventHandlerTest.java
@Test
public void testDiscardStaleWorkingCopies() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IFolder src = javaProject.getProject().getFolder("src");
	IPackageFragmentRoot srcRoot = javaProject.getPackageFragmentRoot(src);
	IPackageFragment mypack = srcRoot.createPackageFragment("mypack", true, null);
	// @formatter:off
	String contents = "package mypack;\n" +
					"public class Foo {" +
					"}\n";
	// @formatter:on
	ICompilationUnit unit = mypack.createCompilationUnit("Foo.java", contents, true, null);
	openDocument(unit, contents, 1);
	assertTrue(unit.isWorkingCopy());

	String oldUri = JDTUtils.getFileURI(srcRoot.getResource());
	String parentUri = JDTUtils.getFileURI(src);
	String newUri = oldUri.replace("mypack", "mynewpack");
	File oldPack = mypack.getResource().getLocation().toFile();
	File newPack = new File(oldPack.getParent(), "mynewpack");
	Files.move(oldPack, newPack);
	assertTrue(unit.isWorkingCopy());
	DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams(Arrays.asList(
		new FileEvent(newUri, FileChangeType.Created),
		new FileEvent(parentUri, FileChangeType.Changed),
		new FileEvent(oldUri, FileChangeType.Deleted)
	));
	new WorkspaceEventsHandler(projectsManager, javaClient, lifeCycleHandler).didChangeWatchedFiles(params);
	assertFalse(unit.isWorkingCopy());
}
 
源代码17 项目: incubator-gobblin   文件: FSDagStateStore.java
/**
 * {@inheritDoc}
 */
@Override
public synchronized void writeCheckpoint(Dag<JobExecutionPlan> dag) throws IOException {
  // write to a temporary name then rename to make the operation atomic when the file system allows a file to be
  // replaced
  String fileName = DagManagerUtils.generateDagId(dag) + DAG_FILE_EXTENSION;
  String serializedDag = serializeDag(dag);

  File tmpCheckpointFile = new File(this.dagCheckpointDir, fileName + ".tmp");
  File checkpointFile = new File(this.dagCheckpointDir, fileName);

  Files.write(serializedDag, tmpCheckpointFile, Charsets.UTF_8);
  Files.move(tmpCheckpointFile, checkpointFile);
}
 
源代码18 项目: incubator-gobblin   文件: GitMonitoringService.java
/**
 * Write the last processed commit githash to the checkpoint file
 * @param gitHash
 * @throws IOException
 */
private void writeCheckpoint(String gitHash) throws IOException {
  // write to a temporary name then rename to make the operation atomic when the file system allows a file to be
  // replaced
  File tmpCheckpointFile = new File(this.repoDir, CHECKPOINT_FILE_TMP);
  File checkpointFile = new File(this.repoDir, CHECKPOINT_FILE);

  Files.write(gitHash, tmpCheckpointFile, Charsets.UTF_8);

  Files.move(tmpCheckpointFile, checkpointFile);
}
 
源代码19 项目: PeerWasp   文件: Move.java
private void moveFileOrFolder(Path srcFile, Path dstFile, boolean wait) throws IOException {
	System.out.println("Move " + srcFile + " to " + dstFile);
	Files.move(srcFile.toFile(), dstFile.toFile());
	if(wait){
		waitForExists(dstFile, WAIT_TIME_LONG);
	}
}
 
源代码20 项目: genie   文件: FetchingCacheServiceImpl.java
private void lookupOrDownload(
    final URI sourceFileUri,
    final File destinationFile
) throws DownloadException, IOException {

    final String uriString = sourceFileUri.toASCIIString();

    log.debug("Lookup: {}", uriString);

    // Unique id to store the resource on local disk
    final String resourceCacheId = getResourceCacheId(sourceFileUri);

    // Get a handle to the resource
    final Resource resource;
    try {
        resource = resourceLoader.getResource(uriString);
    } catch (Throwable t) {
        log.error(
            "Failed to retrieve resource: {}, {} - {}",
            uriString,
            t.getClass().getSimpleName(),
            t.getMessage()
        );
        throw t;
    }

    if (!resource.exists()) {
        throw new DownloadException("Resource not found: " + uriString);
    }

    final long resourceLastModified = resource.lastModified();

    //Handle to resourceCacheId/version
    final File cacheResourceVersionDir = getCacheResourceVersionDir(
        resourceCacheId,
        resourceLastModified
    );

    //Create the resource version dir in cache if it does not exist
    createDirectoryStructureIfNotExists(cacheResourceVersionDir);

    try (
        CloseableLock lock = fileLockFactory.getLock(
            touchCacheResourceVersionLockFile(
                resourceCacheId,
                resourceLastModified
            )
        )
    ) {
        //Critical section begin
        lock.lock();

        //Handle to the resource cached locally
        final File cachedResourceVersionDataFile = getCacheResourceVersionDataFile(
            resourceCacheId,
            resourceLastModified
        );

        if (!cachedResourceVersionDataFile.exists()) {
            log.debug(
                "Cache miss: {} (id: {})",
                uriString,
                resourceCacheId
            );

            // Download the resource into the download file in cache
            // resourceCacheId/version/data.tmp
            final File cachedResourceVersionDownloadFile = getCacheResourceVersionDownloadFile(
                resourceCacheId,
                resourceLastModified
            );
            try (
                InputStream in = resource.getInputStream();
                OutputStream out = new FileOutputStream(cachedResourceVersionDownloadFile)
            ) {
                FileCopyUtils.copy(in, out);
                Files.move(cachedResourceVersionDownloadFile, cachedResourceVersionDataFile);
            }
        } else {
            log.debug(
                "Cache hit: {} (id: {})",
                uriString,
                resourceCacheId
            );
        }

        //Copy from cache data file resourceCacheId/version/DATA_FILE_NAME to targetFile
        Files.copy(cachedResourceVersionDataFile, destinationFile);
        //Critical section end
    } catch (LockException e) {
        throw new DownloadException("Error downloading dependency", e);
    }

    //Clean up any older versions
    cleanUpTaskExecutor.execute(
        new CleanupOlderVersionsTask(resourceCacheId, resourceLastModified)
    );
}