下面列出了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);
}
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"));
}
}
}
}
@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);
}
@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());
}
}
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);
}
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");
}
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------------");
}
@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);
}
}
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());
}
}
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));
}
}
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);
}
}
@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);
}
}
}
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());
}
}
@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());
}
/**
* {@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);
}
/**
* 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);
}
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);
}
}
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)
);
}