Example usage for java.nio.file Files move

List of usage examples for java.nio.file Files move

Introduction

In this page you can find the example usage for java.nio.file Files move.

Prototype

public static Path move(Path source, Path target, CopyOption... options) throws IOException 

Source Link

Document

Move or rename a file to a target file.

Usage

From source file:org.apache.zeppelin.storage.LocalConfigStorage.java

private void atomicWriteToFile(String content, File file) throws IOException {
    File directory = file.getParentFile();
    File tempFile = File.createTempFile(file.getName(), null, directory);
    FileOutputStream out = new FileOutputStream(tempFile);
    try {/*w w  w  .  j av  a 2s .c om*/
        IOUtils.write(content, out);
    } catch (IOException iox) {
        if (!tempFile.delete()) {
            tempFile.deleteOnExit();
        }
        throw iox;
    }
    out.close();
    FileSystem defaultFileSystem = FileSystems.getDefault();
    Path tempFilePath = defaultFileSystem.getPath(tempFile.getCanonicalPath());
    Path destinationFilePath = defaultFileSystem.getPath(file.getCanonicalPath());
    try {
        Files.move(tempFilePath, destinationFilePath, StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException iox) {
        if (!tempFile.delete()) {
            tempFile.deleteOnExit();
        }
        throw iox;
    }
}

From source file:org.kaaproject.kaa.avro.avrogen.compiler.Compiler.java

/**
 * Instantiates a new Compiler./*from w  w w . j  a v a 2s.  c  o m*/
 *
 * @param schemaPath path to file that contains schema
 * @param outputPath destination path for generated sources
 * @param sourceName name of source files
 */
public Compiler(String schemaPath, String outputPath, String sourceName) throws KaaGeneratorException {
    this(sourceName);
    try {
        this.schemas.add(new Schema.Parser().parse(new File(schemaPath)));

        prepareTemplates(true);

        File outputDir = new File(outputPath);
        outputDir.mkdirs();

        String headerPath = outputPath + File.separator + generatedSourceName + ".h";
        String sourcePath = outputPath + File.separator + generatedSourceName + getSourceExtension();

        Files.move(new File(headerTemplateGen()).toPath(), new File(headerPath).toPath(),
                StandardCopyOption.REPLACE_EXISTING);
        Files.move(new File(sourceTemplateGen()).toPath(), new File(sourcePath).toPath(),
                StandardCopyOption.REPLACE_EXISTING);

        this.headerWriter = new PrintWriter(new BufferedWriter(new FileWriter(headerPath, true)));
        this.sourceWriter = new PrintWriter(new BufferedWriter(new FileWriter(sourcePath, true)));
    } catch (Exception ex) {
        LOG.error("Failed to create ouput path: ", ex);
        throw new KaaGeneratorException("Failed to create output path: " + ex.toString());
    }
}

From source file:org.apache.solr.core.StandardDirectoryFactory.java

/**
 * Override for more efficient moves./*from w  w w  .  j a  v  a 2 s.c  o  m*/
 * 
 * Intended for use with replication - use
 * carefully - some Directory wrappers will
 * cache files for example.
 * 
 * You should first {@link Directory#sync(java.util.Collection)} any file that will be 
 * moved or avoid cached files through settings.
 * 
 * @throws IOException
 *           If there is a low-level I/O error.
 */
@Override
public void move(Directory fromDir, Directory toDir, String fileName, IOContext ioContext) throws IOException {

    Directory baseFromDir = getBaseDir(fromDir);
    Directory baseToDir = getBaseDir(toDir);

    if (baseFromDir instanceof FSDirectory && baseToDir instanceof FSDirectory) {

        Path path1 = ((FSDirectory) baseFromDir).getDirectory().toAbsolutePath();
        Path path2 = ((FSDirectory) baseToDir).getDirectory().toAbsolutePath();

        try {
            Files.move(path1.resolve(fileName), path2.resolve(fileName), StandardCopyOption.ATOMIC_MOVE);
        } catch (AtomicMoveNotSupportedException e) {
            Files.move(path1.resolve(fileName), path2.resolve(fileName));
        }
        return;
    }

    super.move(fromDir, toDir, fileName, ioContext);
}

From source file:de.ingrid.interfaces.csw.tools.FileUtils.java

/**
 * Moves a path, retries for timeout ms if moving fails.
 * //from w w w .  j  a  va 2 s.  co  m
 * @param src
 * @param dest
 * @param timeout
 * @throws IOException
 */
public static void waitAndMove(Path src, Path dest, long timeout) throws IOException {
    long time = 0;
    boolean isMoved = false;
    long pause = ApplicationProperties.getInteger(ConfigurationKeys.FILE_OPERATION_RETRY_TIMEOUT, 1000);
    while (time < timeout && !isMoved) {
        try {
            Files.move(src, dest, ATOMIC_MOVE);
            isMoved = true;
        } catch (IOException e) {
            log.warn("Move " + src + " to " + dest + " failed.", e);
            log.warn("Sleep " + pause + "ms and retry.");
            try {
                Thread.sleep(pause);
            } catch (InterruptedException e1) {
                log.error("Waiting for moving " + src + " to " + dest + " failed. Got iterrupted", e1);
                throw new IOException(e1);
            }
            time += pause;
            if (time >= timeout) {
                throw new IOException("Move " + src + " to " + dest + " failed after " + timeout + "ms.");
            }
        }
    }
}

From source file:org.commonjava.maven.ext.cli.CliTest.java

@Test
public void checkLocalRepositoryWithDefaultsAndModifiedUserSettings() throws Exception {
    boolean restore = false;
    Path source = Paths.get(
            System.getProperty("user.home") + File.separatorChar + ".m2" + File.separatorChar + "settings.xml");
    Path backup = Paths.get(source.toString() + '.' + UUID.randomUUID().toString());
    Path tmpSettings = Paths.get(getClass().getResource("/settings-test.xml").getFile());

    try {/*w w  w.  j a  va  2s . com*/
        if (source.toFile().exists()) {
            System.out.println("Backing up settings.xml to " + backup);
            restore = true;
            Files.move(source, backup, StandardCopyOption.ATOMIC_MOVE);
        }
        Files.copy(tmpSettings, source);

        Cli c = new Cli();
        executeMethod(c, "run", new Object[] { new String[] {} });

        ManipulationSession session = (ManipulationSession) FieldUtils.readField(c, "session", true);
        MavenSession ms = (MavenSession) FieldUtils.readField(session, "mavenSession", true);

        assertTrue(ms.getRequest().getLocalRepository().getBasedir()
                .equals(ms.getRequest().getLocalRepositoryPath().toString()));
        assertTrue(ms.getLocalRepository().getBasedir()
                .equals(System.getProperty("user.home") + File.separatorChar + ".m2-mead-test"));

    } finally {
        if (restore) {
            Files.move(backup, source, StandardCopyOption.ATOMIC_MOVE);
        } else {
            Files.delete(source);
        }
    }
}

From source file:org.codice.ddf.configuration.store.ConfigurationFileDirectory.java

void moveFile(Path source, Path destination) throws IOException {
    Files.move(source, destination.resolve(source.getFileName()), REPLACE_EXISTING);
}

From source file:org.roda.core.storage.fs.FSUtils.java

/**
 * Moves a directory/file from one path to another
 * //w w  w  .j  a  va  2 s  .c om
 * @param sourcePath
 *          source path
 * @param targetPath
 *          target path
 * @param replaceExisting
 *          true if the target directory/file should be replaced if it already
 *          exists; false otherwise
 * @throws AlreadyExistsException
 * @throws GenericException
 * @throws NotFoundException
 * 
 */
public static void move(final Path sourcePath, final Path targetPath, boolean replaceExisting)
        throws AlreadyExistsException, GenericException, NotFoundException {

    // check if we can replace existing
    if (!replaceExisting && FSUtils.exists(targetPath)) {
        throw new AlreadyExistsException("Cannot copy because target path already exists: " + targetPath);
    }

    // ensure parent directory exists or can be created
    try {
        if (targetPath != null) {
            Files.createDirectories(targetPath.getParent());
        }
    } catch (FileAlreadyExistsException e) {
        // do nothing
    } catch (IOException e) {
        throw new GenericException("Error while creating target directory parent folder", e);
    }

    CopyOption[] copyOptions = replaceExisting ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
            : new CopyOption[] {};

    if (FSUtils.isDirectory(sourcePath)) {
        try {
            Files.move(sourcePath, targetPath, copyOptions);
        } catch (DirectoryNotEmptyException e) {
            // 20160826 hsilva: this might happen in some filesystems (e.g. XFS)
            // because moving a directory implies also moving its entries. In Ext4
            // this doesn't happen.
            LOGGER.debug("Moving recursively, as a fallback & instead of a simple move, from {} to {}",
                    sourcePath, targetPath);
            moveRecursively(sourcePath, targetPath, replaceExisting);
        } catch (IOException e) {
            throw new GenericException("Error while moving directory from " + sourcePath + " to " + targetPath,
                    e);
        }
    } else {
        try {
            Files.move(sourcePath, targetPath, copyOptions);
        } catch (NoSuchFileException e) {
            throw new NotFoundException("Could not find resource to move", e);
        } catch (IOException e) {
            throw new GenericException("Error while copying one file into another", e);
        }
    }
}

From source file:org.sigmah.server.file.impl.BackupArchiveJob.java

/**
 * {@inheritDoc}//from ww  w . jav  a2s .  co m
 */
@Override
public void run() {

    final Path tempArchiveFile = arguments.tempArchiveFile;
    final Path finalArchiveFile = arguments.finalArchiveFile;

    try (final ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(
            Files.newOutputStream(tempArchiveFile))) {

        zipOutputStream.setMethod(ZipOutputStream.DEFLATED);
        zipOutputStream.setLevel(Deflater.BEST_COMPRESSION);

        final RepositoryElement repository = buildOrgUnitRepository(arguments.backup, arguments.userId);
        repository.setName("");

        zipRepository(repository, zipOutputStream, "");

        // TODO Delete existing previous organization file(s).

        // Renames temporary '.tmp' file to complete '.zip' file.
        Files.move(tempArchiveFile, finalArchiveFile, StandardCopyOption.REPLACE_EXISTING);

    } catch (final Throwable t) {

        if (LOG.isErrorEnabled()) {
            LOG.error("An error occurred during backup archive generation process.", t);
        }

        try {

            Files.deleteIfExists(tempArchiveFile);
            Files.deleteIfExists(finalArchiveFile);

        } catch (final IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("An error occurred while deleting archive error file.", e);
            }
        }
    }
}

From source file:ch.bender.evacuate.Helper.java

/**
 * If the given target is already present, the method retains this older version in a kind of
 * FIFO buffer (but persistent on disk). The given MaxBackups number indicates how many such
 * backups are kept.//w  w w .j  av a  2s .  c  o m
 * <p>
 * This routine is valid for files and directories. With files, the numbering suffix is done
 * before the last dot in the file name, with directories the number suffix is appended at the
 * end. 
 * <p>
 * Example: target is "Target.txt" and there are already present:
 * <pre>
 *     Target.txt
 *     Target_01.txt
 *     Target_02.txt
 * <pre>
 * Target_02.txt is renamed to Target_03.txt, Target_01.txt to Target_02.txt and Target.txt Target_01.txt.
 * <p>
 * If MaxBackup would be 3, then Target_02.txt would have been deleted instead renamed.
 * <p>   
 * 
 * @param aTarget
 * @param aMaxBackups
 * @param aFailedPreparations 
 * @throws IOException
 */
public static void prepareTrashChain(Path aTarget, int aMaxBackups, Map<Path, Throwable> aFailedPreparations) {
    myLog.debug("preparing trash chain for " + aTarget.toString());

    try {

        int i = aMaxBackups - 1;

        while (i > 0) {
            Path targetUpper = appendNumberSuffix(aTarget, i);
            Path targetLower = (i > 1) ? appendNumberSuffix(aTarget, i - 1) : aTarget;

            i--;

            if (Files.notExists(targetUpper) && Files.notExists(targetLower)) {
                continue;
            }

            if (Files.exists(targetUpper)) {
                myLog.info("There are already " + (i + 2) + " trashed versions of " + aTarget.toString()
                        + ". Deleting the oldest one");

                if (Files.exists(targetUpper)) {
                    if (Files.isDirectory(targetUpper)) {
                        Helper.deleteDirRecursive(targetUpper);
                    } else {
                        Files.delete(targetUpper);
                    }
                }
            }

            if (Files.notExists(targetLower)) {
                continue;
            }

            myLog.debug("Renaming " + targetLower.toString() + " to " + targetUpper.toString());
            Files.move(targetLower, targetUpper, StandardCopyOption.ATOMIC_MOVE);
        }
    } catch (Throwable e) {
        aFailedPreparations.put(aTarget, e);
    }
}

From source file:org.wso2.appserver.integration.tests.session.persistence.WSAS2060SessionPersistenceTestCase.java

@AfterClass(alwaysRun = true)
public void restoreServer() throws Exception {
    sessionCookie = loginLogoutClient.login();
    webAppAdminClient = new WebAppAdminClient(backendURL, sessionCookie);
    if (userMode.equals(TestUserMode.TENANT_USER)) {
        webAppAdminClient.deleteWebAppFile(HELLOWORLD_WEBAPP_NAME + ".war",
                asServer.getInstance().getHosts().get("default"));
    }// w ww.  jav a  2  s.com
    //Revert and restart only once
    --isRestarted;
    if (isRestarted == 0) {
        if (Files.exists(Paths.get(CONTEXT_XML_PATH + ".backup"))) {
            Files.move(Paths.get(CONTEXT_XML_PATH + ".backup"), Paths.get(CONTEXT_XML_PATH),
                    new CopyOption[] { StandardCopyOption.REPLACE_EXISTING });
        }
        if (Files.exists(Paths.get(CARBON_XML_PATH + ".backup"))) {
            Files.move(Paths.get(CARBON_XML_PATH + ".backup"), Paths.get(CARBON_XML_PATH),
                    new CopyOption[] { StandardCopyOption.REPLACE_EXISTING });
        }
        serverConfigurationManager.restartGracefully();
    }
}