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.kalypso.commons.resources.SetContentHelper.java

public void setFileContents(final IFile file, final boolean force, final boolean keepHistory,
        final IProgressMonitor monitor, final String charset) throws CoreException {
    final String oldCharset = findCurrentCharset(file);
    final String newCharset = findNewCharset(file, charset, oldCharset);

    final File javaFile = file.getLocation().toFile();

    // save file to backup
    final Path filePath = javaFile.toPath();

    final String fileName = javaFile.getAbsolutePath();
    final String backupFileName = fileName + BCKUP_SUFFIX + System.currentTimeMillis();
    final File backupFile = new File(backupFileName);

    try {/*from w  ww  . j a v  a2 s. c  o  m*/
        writeContents(backupFile, newCharset, monitor);

        /* rename backup to new file */
        Files.move(backupFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING);

        file.refreshLocal(IFile.DEPTH_ZERO, new NullProgressMonitor());

        if (newCharset != null && !ObjectUtils.equals(oldCharset, newCharset))
            file.setCharset(newCharset, new SubProgressMonitor(monitor, 1000));
    } catch (final Throwable e) {
        throw new CoreException(StatusUtilities.statusFromThrowable(e,
                Messages.getString("org.kalypso.commons.resources.SetContentHelper.2"))); //$NON-NLS-1$
    }

    // enclose in finally?
    monitor.done();
}

From source file:org.apache.flink.tests.util.FlinkDistribution.java

@Override
public void afterTestSuccess() {
    try {/*from ww  w .  j  av  a2  s .  c om*/
        stopFlinkCluster();
    } catch (IOException e) {
        LOG.error("Failure while shutting down Flink cluster.", e);
    }

    final Path originalConfig = conf.resolve(FLINK_CONF_YAML);
    final Path backupConfig = conf.resolve(FLINK_CONF_YAML_BACKUP);

    try {
        Files.move(backupConfig, originalConfig, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        LOG.error("Failed to restore flink-conf.yaml", e);
    }

    for (AutoCloseable fileToDelete : filesToDelete) {
        try {
            fileToDelete.close();
        } catch (Exception e) {
            LOG.error("Failure while cleaning up file.", e);
        }
    }
}

From source file:org.structr.media.FrameGrabberProcess.java

@Override
public Image processExited(int exitCode) {

    final App app = StructrApp.getInstance(securityContext);

    if (exitCode == 0) {

        try (final Tx tx = app.tx()) {

            // move converted file into place
            final java.io.File diskFile = new java.io.File(outputFileName + fileExtension);
            final java.io.File dstFile = new java.io.File(outputFileName);
            if (diskFile.exists()) {

                Files.move(diskFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                FileHelper.updateMetadata(newFile);

                // create link between the two videos
                inputFile.setProperty(StructrApp.key(VideoFile.class, "posterImage"), newFile);
            }/*from  www  . j  av a 2 s .co  m*/

            tx.success();

        } catch (FrameworkException | IOException fex) {
            logger.warn("", fex);
        }

    } else {

        // delete file, conversion has failed
        try (final Tx tx = app.tx()) {

            app.delete(newFile);
            tx.success();

        } catch (FrameworkException fex) {
            logger.warn("", fex);
        }

    }

    return newFile;
}

From source file:azkaban.execapp.FlowPreparer.java

/**
 * Prepare the project directory./* w  ww  . j  a va2 s  .c o m*/
 *
 * @param pv ProjectVersion object
 * @throws ProjectManagerException
 * @throws IOException
 */
@VisibleForTesting
void setupProject(final ProjectVersion pv) throws ProjectManagerException, IOException {
    final int projectId = pv.getProjectId();
    final int version = pv.getVersion();

    final String projectDir = String.valueOf(projectId) + "." + String.valueOf(version);
    if (pv.getInstalledDir() == null) {
        pv.setInstalledDir(new File(projectsDir, projectDir));
    }

    // If directory exists. Assume its prepared and skip.
    if (pv.getInstalledDir().exists()) {
        log.info("Project already cached. Skipping download. " + pv);
        return;
    }

    log.info("Preparing Project: " + pv);

    File tempDir = new File(projectsDir, "_temp." + projectDir + "." + System.currentTimeMillis());

    // TODO Why mkdirs? This path should be already set up.
    tempDir.mkdirs();

    ProjectFileHandler projectFileHandler = null;
    try {
        projectFileHandler = requireNonNull(projectLoader.getUploadedFile(projectId, version));
        checkState("zip".equals(projectFileHandler.getFileType()));

        log.info("Downloading zip file.");
        final File zipFile = requireNonNull(projectFileHandler.getLocalFile());
        final ZipFile zip = new ZipFile(zipFile);
        Utils.unzip(zip, tempDir);

        Files.move(tempDir.toPath(), pv.getInstalledDir().toPath(), StandardCopyOption.ATOMIC_MOVE);

        log.warn(String.format("Project Preparation complete. [%s]", pv));
    } finally {

        if (projectFileHandler != null) {
            projectFileHandler.deleteLocalFile();
        }

        // Clean up: Remove tempDir if exists
        FileUtils.deleteDirectory(tempDir);
    }
}

From source file:org.wisdom.maven.osgi.BundlePackager.java

/**
 * Creates the bundle./* www  . j  a  v a 2s  .  co m*/
 *
 * @param basedir the project's base directory
 * @param output  the output file
 * @throws IOException occurs when the bundle cannot be built correctly.
 */
public static void bundle(File basedir, File output, Reporter reporter) throws IOException {
    ProjectScanner scanner = new ProjectScanner(basedir);

    // Loads the properties inherited from Maven.
    Properties instructions = readMavenProperties(basedir);
    // Loads the properties from the BND file.
    Properties fromBnd = readInstructionsFromBndFile(basedir);
    if (fromBnd == null) {
        // No bnd files, use default instructions
        instructions = populatePropertiesWithDefaults(basedir, instructions, scanner);
    } else {
        // We have a BND file.
        // Do we have to merge ?
        String noDefaultValue = fromBnd.getProperty("-no-default");
        if (!"true".equalsIgnoreCase(noDefaultValue)) {
            // So we need to merge the default with the bnd files
            // 1) merge the instructions from the bnd files with the default
            // 2) merge the resulting set of instruction onto the maven properties
            // (and override the default)
            instructions = Instructions.mergeAndOverrideExisting(instructions,
                    populatePropertiesWithDefaults(basedir, fromBnd, scanner));
        } else {
            instructions = Instructions.mergeAndOverrideExisting(instructions, fromBnd);
        }
    }

    // Manage Embedded dependencies
    DependencyEmbedder ed = new DependencyEmbedder(instructions, reporter);
    instructions = ed.generate(instructions, org.wisdom.maven.osgi.Classpath.load(basedir));

    // Integrate custom headers added by other plugins.
    instructions = mergeExtraHeaders(basedir, instructions);

    // For debugging purpose, dump the instructions to target/osgi/instructions.properties
    FileOutputStream fos = null;
    try {
        File out = new File(basedir, "target/osgi/instructions.properties");
        fos = new FileOutputStream(out);
        instructions.store(fos, "Wisdom BND Instructions");
    } catch (IOException e) { // NOSONAR
        // Ignore it.
    } finally {
        IOUtils.closeQuietly(fos);
    }

    // Instructions loaded, start the build sequence.
    final Jar[] jars = org.wisdom.maven.osgi.Classpath.computeClassPath(basedir);

    File bnd;
    File ipojo;
    Builder builder = null;
    try {
        builder = getOSGiBuilder(basedir, instructions, jars);
        // The next sequence is weird
        // First build the bundle with the given instruction
        // Then analyze to apply the plugin and fix
        // finally, rebuild with the updated metadata
        // Without the first build, embedded dependencies and private packages from classpath are not analyzed.
        builder.build();
        builder.analyze();
        builder.build();

        reportErrors(builder.getWarnings(), builder.getErrors(), reporter);
        bnd = File.createTempFile("bnd-", ".jar");
        ipojo = File.createTempFile("ipojo-", ".jar");
        builder.getJar().write(bnd);
    } catch (Exception e) {
        throw new IOException("Cannot build the OSGi bundle", e);
    } finally {
        if (builder != null) {
            builder.close();
        }
    }

    final Set<String> elements = org.wisdom.maven.osgi.Classpath.computeClassPathElement(basedir);
    Classpath classpath = new Classpath(elements);
    Pojoization pojoization = new Pojoization();
    pojoization.pojoization(bnd, ipojo, new File(basedir, "src/main/resources"), classpath.createClassLoader());
    reportErrors(pojoization.getWarnings(), pojoization.getErrors(), reporter);

    Files.move(Paths.get(ipojo.getPath()), Paths.get(output.getPath()), StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.frederikam.gensokyobot.Config.java

/**
 * Makes sure the requested config file exists in the current format. Will attempt to migrate old formats to new ones
 * old files will be renamed to filename.ext.old to preserve any data
 *
 * @param name relative name of a config file, without the file extension
 * @return a handle on the requested file
 *//*from ww w .ja v a 2s.  c om*/
private static File loadConfigFile(String name) throws IOException {
    String yamlPath = "./" + name + ".yaml";
    String jsonPath = "./" + name + ".json";
    File yamlFile = new File(yamlPath);
    if (!yamlFile.exists() || yamlFile.isDirectory()) {
        log.warn("Could not find file '" + yamlPath + "', looking for legacy '" + jsonPath + "' to rewrite");
        File json = new File(jsonPath);
        if (!json.exists() || json.isDirectory()) {
            //file is missing
            log.error("No " + name + " file is present. Bot cannot run without it. Check the documentation.");
            throw new FileNotFoundException("Neither '" + yamlPath + "' nor '" + jsonPath + "' present");
        } else {
            //rewrite the json to yaml
            Yaml yaml = new Yaml();
            String fileStr = FileUtils.readFileToString(json, "UTF-8");
            //remove tab character from json file to make it a valid YAML file
            fileStr = fileStr.replaceAll("\t", "");
            @SuppressWarnings("unchecked")
            Map<String, Object> configFile = (Map) yaml.load(fileStr);
            yaml.dump(configFile, new FileWriter(yamlFile));
            Files.move(Paths.get(jsonPath), Paths.get(jsonPath + ".old"), REPLACE_EXISTING);
            log.info("Migrated file '" + jsonPath + "' to '" + yamlPath + "'");
        }
    }

    return yamlFile;
}

From source file:org.obiba.opal.server.UpgradeCommand.java

private void upgradeOrientDb() {
    log.info("Upgrading orientdb");
    File exportFile = null;//from   w w w  . j a va 2 s  . c  om
    File tmpFile = null;
    Path configBackup = Paths.get(String.format("%s.bak", opalConfigPath));
    Path config = Paths.get(opalConfigPath);

    try {
        tmpFile = File.createTempFile("opal_orientdb_export", null);
        String exportFilePrefix = tmpFile.getAbsolutePath();
        exportFile = Paths.get(exportFilePrefix + ".gz").toFile();

        exportOpalConfig(opalConfigPath, exportFilePrefix);
        Files.move(config, configBackup, StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException e) {
        if (exportFile != null && exportFile.exists())
            exportFile.delete();

        throw Throwables.propagate(e);
    } finally {
        if (tmpFile != null)
            tmpFile.delete();
    }

    try (ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_PATHS)) {
        OrientDbService orientDbService = ctx.getBean("orientDbService", OrientDbService.class);
        orientDbService.importDatabase(exportFile);
        log.info("Upgraded orientdb successfully");

        try {
            FileUtils.deleteDirectory(configBackup.toFile());
        } catch (Exception e) {
            log.error("Error cleaning up orientdb upgrade back up directory. Ignoring.", e);
        }
    } catch (IOException e) {
        //roll back
        try {
            FileUtils.deleteDirectory(config.toFile());
            Files.move(configBackup, config, StandardCopyOption.ATOMIC_MOVE);
        } catch (Exception ex) {
            log.error("Error in orientdb upgrade rollback. Ignoring.", ex);
        }

        throw Throwables.propagate(e);
    } finally {
        if (exportFile != null && exportFile.exists())
            exportFile.delete();
    }
}

From source file:com.frostwire.gui.library.DownloadTask.java

@Override
public void run() {
    if (!isRunning()) {
        return;/* ww  w. j a va2 s .c  om*/
    }

    File lastFile = null;

    try {
        setProgress(0);

        if (!savePath.exists()) {
            savePath.mkdirs();
        }

        long totalBytes = getTotalBytes();
        long totalWritten = 0;

        for (int i = 0; i < fds.length; i++) {
            if (!isRunning()) {
                return;
            }

            currentFD = fds[i];

            GUIMediator.safeInvokeLater(new Runnable() {
                public void run() {
                    String status = String.format("%s from %s - %s", I18n.tr("Downloading"), device.getName(),
                            currentFD.title);
                    LibraryMediator.instance().getLibrarySearch().pushStatus(status);
                }
            });

            URL url = new URL(device.getDownloadURL(currentFD));

            InputStream is = null;
            OutputStream fos = null;

            try {
                is = url.openStream();

                String filename = OSUtils.escapeFilename(FilenameUtils.getName(currentFD.filePath));
                File file = buildFile(savePath, filename);
                Path incompleteFile = buildIncompleteFile(file).toPath();
                lastFile = file.getAbsoluteFile();

                fos = Files.newOutputStream(incompleteFile, StandardOpenOption.CREATE);// new FileOutputStream(incompleteFile);

                byte[] buffer = new byte[4 * 1024];
                int n = 0;

                while ((n = is.read(buffer, 0, buffer.length)) != -1) {
                    if (!isRunning()) {
                        return;
                    }

                    fos.write(buffer, 0, n);
                    fos.flush();
                    totalWritten += n;
                    setProgress((int) ((totalWritten * 100) / totalBytes));

                    if (getProgress() % 5 == 0) {
                        GUIMediator.safeInvokeLater(new Runnable() {
                            public void run() {
                                String status = String.format("%d%% %s from %s - %s", getProgress(),
                                        I18n.tr("Downloading"), device.getName(), currentFD.title);
                                LibraryMediator.instance().getLibrarySearch().pushStatus(status);
                            }
                        });
                    }

                    //System.out.println("Progress: " + getProgress() + " Total Written: " + totalWritten + " Total Bytes: " + totalBytes);
                }

                close(fos);
                Files.move(incompleteFile, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } finally {
                close(is);
                close(fos);
            }
        }

        setProgress(100);
    } catch (Throwable e) {
        e.printStackTrace();
        onError(e);

        GUIMediator.safeInvokeLater(new Runnable() {
            public void run() {
                LibraryMediator.instance().getLibrarySearch()
                        .pushStatus(I18n.tr("Wi-Fi download error. Please try again."));
            }
        });
    } finally {
        GUIMediator.safeInvokeLater(new Runnable() {
            public void run() {
                LibraryMediator.instance().getLibrarySearch().revertStatus();
            }
        });

        if (lastFile != null) {
            GUIMediator.launchExplorer(lastFile);
        }
    }

    stop();
}

From source file:misc.FileHandler.java

/**
 * Copies the source file with the given options to the target file. The
 * source is first copied to the system's default temporary directory and
 * the temporary copy is then moved to the target file. In order to avoid
 * performance problems, the file is directly copied from the source to a
 * temporary file in the target directory first, if the temporary directory
 * and the target file lie on a different <code>FileStore</code>. The
 * temporary file is also moved to the target file.
 * /*from ww  w  . j  a  v  a 2 s. c  o  m*/
 * @param source
 *            the file to copy.
 * @param target
 *            the target location where the file should be stored. Must not
 *            be identical with source. The file might or might not exist.
 *            The parent directory must exist.
 * @param replaceExisting
 *            <code>true</code>, if the target file may be overwritten.
 *            Otherwise, <code>false</code>.
 * @return <code>true</code>, if the file was successfully copied.
 *         Otherwise, <code>false</code>.
 */
public static boolean copyFile(Path source, Path target, boolean replaceExisting) {
    if ((source == null) || !Files.isReadable(source)) {
        throw new IllegalArgumentException("source must exist and be readable!");
    }
    if (target == null) {
        throw new IllegalArgumentException("target may not be null!");
    }
    if (source.toAbsolutePath().normalize().equals(target.toAbsolutePath().normalize())) {
        throw new IllegalArgumentException("source and target must not match!");
    }

    boolean success = false;
    Path tempFile = null;

    target = target.normalize();

    try {
        tempFile = FileHandler.getTempFile(target);

        if (tempFile != null) {
            Files.copy(source, tempFile, StandardCopyOption.COPY_ATTRIBUTES,
                    StandardCopyOption.REPLACE_EXISTING);
            if (replaceExisting) {
                Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING);
            } else {
                Files.move(tempFile, target);
            }
            success = true;
        }
    } catch (IOException e) {
        Logger.logError(e);
    } finally {
        if (tempFile != null) {
            try {
                Files.deleteIfExists(tempFile);
            } catch (IOException eDelete) {
                Logger.logError(eDelete);
            }
        }
    }

    return success;
}

From source file:com.arpnetworking.metrics.common.tailer.FilePositionStore.java

private void flush() {
    // Age out old state
    final DateTime now = DateTime.now();
    final DateTime oldest = now.minus(_retention);
    final long sizeBefore = _state.size();
    final Iterator<Map.Entry<String, Descriptor>> iterator = _state.entrySet().iterator();
    while (iterator.hasNext()) {
        final Map.Entry<String, Descriptor> entry = iterator.next();
        if (!oldest.isBefore(entry.getValue().getLastUpdated())) {
            // Remove old descriptors
            iterator.remove();//from   w w  w  . j ava  2s. com
        } else {
            // Mark retained descriptors as flushed
            entry.getValue().flush();
        }
    }
    final long sizeAfter = _state.size();
    if (sizeBefore != sizeAfter) {
        LOGGER.debug().setMessage("Removed old entries from file position store")
                .addData("sizeBefore", sizeBefore).addData("sizeAfter", sizeAfter).log();
    }

    // Persist the state to disk
    try {
        final Path temporaryFile = Paths.get(_file.toAbsolutePath().toString() + ".tmp");
        OBJECT_MAPPER.writeValue(temporaryFile.toFile(), _state);
        Files.move(temporaryFile, _file, StandardCopyOption.REPLACE_EXISTING);

        LOGGER.debug().setMessage("Persisted file position state to disk").addData("size", _state.size())
                .addData("file", _file).log();
    } catch (final IOException ioe) {
        throw Throwables.propagate(ioe);
    } finally {
        _lastFlush = now;
    }
}