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:uk.ac.sanger.cgp.wwdocker.interfaces.Workflow.java

default void iniUpdate(List<File> inisFrom, BaseConfiguration config, HostStatus hs) {
    String iniBaseTo = config.getString("wfl_inis");
    if (!iniBaseTo.endsWith("/")) {
        iniBaseTo = iniBaseTo.concat("/");
    }//from  ww  w.  ja va  2s .co m
    iniBaseTo = iniBaseTo.concat(hs.name()).concat("/");
    File dirCreate = new File(iniBaseTo);
    if (!dirCreate.exists()) {
        if (!dirCreate.mkdirs()) {
            throw new RuntimeException("Failed to create full path: " + dirCreate.getAbsolutePath());
        }
    }
    for (File iniFrom : inisFrom) {
        File iniTo = new File(iniBaseTo.concat(iniFrom.getName()));
        try {
            Files.move(iniFrom.toPath(), iniTo.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:de.ks.file.FileStore.java

public void saveInFileStore(FileReference ref, File file) {
    if (!file.exists()) {
        throw new IllegalArgumentException("File " + file + " has to exist");
    }/*from w w  w. jav a 2s  . co  m*/
    if (ref.getMd5Sum() == null) {
        throw new IllegalArgumentException("MD5 sum has to be calculated");
    }

    Path dir = Paths.get(getFileStoreDir(), ref.getMd5Sum());
    try {
        Files.createDirectories(dir);
    } catch (IOException e) {
        log.error("Could not store create parent directory {}", dir, e);
        return;
    }

    Path targetPath = Paths.get(getFileStoreDir(), ref.getMd5Sum(), ref.getName());
    if (options.shouldCopy()) {
        try {
            Files.copy(file.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            log.error("could not copy {} to {}", file.toPath(), targetPath);
            throw new RuntimeException(e);
        }
    } else {
        try {
            Files.move(file.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            log.error("could not move {} to {}", file.toPath(), targetPath);
            throw new RuntimeException(e);
        }
    }
}

From source file:joachimeichborn.geotag.io.jpeg.PictureMetadataWriter.java

private void replaceOriginalWithAnnotated(final Path originalFile, final Path annotatedFile)
        throws IOException {
    Files.move(annotatedFile, originalFile, StandardCopyOption.REPLACE_EXISTING);
}

From source file:media_organizer.MediaInspector.java

@SuppressWarnings("unchecked")
public void unique_file_generator() {
    Iterator<File> iter = FileUtils.iterateFilesAndDirs(topStartDirectory.toFile(), TrueFileFilter.INSTANCE,
            new IOFileFilter() {
                @Override//from ww w  . jav  a2 s. c om
                public boolean accept(File file) {
                    try {
                        return pureDirectory(file);
                    } catch (IOException ex) {
                        return false;
                    }
                }

                @Override
                public boolean accept(File dir, String name) {
                    try {
                        return pureDirectory(dir);
                    } catch (IOException ex) {
                        return false;
                    }
                }
            });

    File n;
    try {
        while (iter.hasNext()) {
            n = iter.next();

            if (!pureDirectory(n)) {
                if (n.getAbsolutePath().contains("DS_Store")) {
                    continue;
                }
                String cksm = getChecksum(n, false);
                if (!globalChecksumList.contains(cksm)) {
                    globalChecksumList.add(cksm);
                    // Rename or copy file into the new name and store the file path in list
                    String create_time_str = get_file_creation_time(n);
                    String temp_name = create_time_str + "_" + cksm + "."
                            + FilenameUtils.getExtension(n.getAbsolutePath());
                    File tempFile = new File(tempDirectory.toString() + "/" + temp_name);
                    System.out.println("Copying " + n.getAbsolutePath() + " to temp location as "
                            + tempFile.getAbsolutePath());
                    Files.copy(n.toPath(), tempFile.toPath(), COPY_ATTRIBUTES);

                    String new_create_time_str = get_file_creation_time(tempFile);
                    String new_name = new_create_time_str + "_" + cksm + "."
                            + FilenameUtils.getExtension(n.getAbsolutePath());
                    File newFile = new File(destDirectory.toString() + "/" + new_name);
                    System.out.println(
                            "Moving " + tempFile.getAbsolutePath() + " as " + newFile.getAbsolutePath());
                    Files.move(tempFile.toPath(), newFile.toPath(), ATOMIC_MOVE);
                } else {
                    System.out.println("\nSkipping Duplicate file: " + n.getName() + "\n");
                }
            }
        }
        System.out.println("\n");
    } catch (IOException ex) {
        System.out.format(ex.getMessage());
    } finally {
        if (tmp_directory.exists()) {
            tmp_directory.delete();
        }
    }
}

From source file:com.seleniumtests.reporter.logger.Snapshot.java

/**
 * Rename HTML and PNG files so that they do not present an uuid
 * New name is <test_name>_<step_idx>_<snapshot_idx>_<step_name>_<uuid>
 * @param testStep/*from   w  ww. j  a  v a  2  s.  com*/
 * @param stepIdx         number of this step
 * @param snapshotIdx   number of this snapshot for this step
 * @param userGivenName   name specified by user, rename to this name
 */
public void rename(final TestStep testStep, final int stepIdx, final int snapshotIdx,
        final String userGivenName) {
    String newBaseName;
    if (userGivenName == null) {
        newBaseName = String.format("%s_%d-%d_%s-",
                StringUtility.replaceOddCharsFromFileName(CommonReporter.getTestName(testStep.getTestResult())),
                stepIdx, snapshotIdx, StringUtility.replaceOddCharsFromFileName(testStep.getName()));
    } else {
        newBaseName = StringUtility.replaceOddCharsFromFileName(userGivenName);
    }

    if (screenshot.getHtmlSourcePath() != null) {
        String oldFullPath = screenshot.getFullHtmlPath();
        String oldPath = screenshot.getHtmlSourcePath();
        File oldFile = new File(oldPath);
        String folderName = "";
        if (oldFile.getParent() != null) {
            folderName = oldFile.getParent().replace(File.separator, "/") + "/";
        }

        String newName = newBaseName + FilenameUtils.getBaseName(oldFile.getName());
        newName = newName.substring(0, Math.min(50, newName.length())) + "."
                + FilenameUtils.getExtension(oldFile.getName());

        // if file cannot be moved, go back to old name
        try {
            oldFile = new File(oldFullPath);
            if (SeleniumTestsContextManager.getGlobalContext().getOptimizeReports()) {
                screenshot.setHtmlSourcePath(folderName + newName + ".zip");
                oldFile = FileUtility.createZipArchiveFromFiles(Arrays.asList(oldFile));
            } else {
                screenshot.setHtmlSourcePath(folderName + newName);
            }

            FileUtils.copyFile(oldFile, new File(screenshot.getFullHtmlPath()));
            new File(oldFullPath).delete();

        } catch (IOException e) {
            screenshot.setHtmlSourcePath(oldPath);
        }
    }
    if (screenshot.getImagePath() != null) {
        String oldFullPath = screenshot.getFullImagePath();
        String oldPath = screenshot.getImagePath();
        File oldFile = new File(oldPath);
        String folderName = "";
        if (oldFile.getParent() != null) {
            folderName = oldFile.getParent().replace(File.separator, "/") + "/";
        }

        String newName = newBaseName + FilenameUtils.getBaseName(oldFile.getName());
        newName = newName.substring(0, Math.min(50, newName.length())) + "."
                + FilenameUtils.getExtension(oldFile.getName());
        screenshot.setImagePath(folderName + newName);

        // if file cannot be moved, go back to old name
        try {
            Files.move(Paths.get(oldFullPath), Paths.get(screenshot.getFullImagePath()),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            screenshot.setImagePath(oldPath);
        }
    }
}

From source file:org.nuxeo.ecm.core.api.impl.blob.FileBlob.java

/**
 * Moves this blob's temporary file to a new non-temporary location.
 * <p>/*from w  w  w. j  a va2 s.  c o  m*/
 * The move is done as atomically as possible.
 *
 * @since 7.2
 */
public void moveTo(File dest) throws IOException {
    if (!isTemporary) {
        throw new IOException("Cannot move non-temporary file: " + file);
    }
    Path path = file.toPath();
    Path destPath = dest.toPath();
    try {
        Files.move(path, destPath, ATOMIC_MOVE);
        file = dest;
    } catch (AtomicMoveNotSupportedException e) {
        // Do a copy through a tmp file on the same filesystem then atomic rename
        Path tmp = Files.createTempFile(destPath.getParent(), null, null);
        try {
            Files.copy(path, tmp, REPLACE_EXISTING);
            Files.delete(path);
            Files.move(tmp, destPath, ATOMIC_MOVE);
            file = dest;
        } catch (IOException ioe) {
            // don't leave tmp file in case of error
            Files.deleteIfExists(tmp);
            throw ioe;
        }
    }
    isTemporary = false;
}

From source file:com.github.thorqin.webapi.FileManager.java

public void moveTo(String fileId, File destPath, boolean replaceExisting) throws IOException {
    File dataFile = new File(uploadDir + "/" + fileId + ".data");
    if (replaceExisting)
        Files.move(dataFile.toPath(), destPath.toPath(), StandardCopyOption.REPLACE_EXISTING);
    else/*from   www  .  j  av a  2 s . c  o  m*/
        Files.move(dataFile.toPath(), destPath.toPath());
    deleteFile(fileId);
}

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

/**
 * run//from w  w  w .  j  av  a2s  .  c  o  m
 * <p>
 * @throws Exception 
 */
public void run() throws Exception {
    checkDirectories();
    initExcludeMatchers();

    myEvacuateCandidates = new TreeMap<>();
    myFailedChainPreparations = Collections.synchronizedMap(new HashMap<>());
    myFutures = new HashSet<>();
    myExclusionDirCount = 0;
    myEvacuationDirCount = 0;
    myExclusionFileCount = 0;
    myEvacuationFileCount = 0;

    Files.walkFileTree(myBackupDir, new SimpleFileVisitor<Path>() {
        /**
         * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException)
         */
        @Override
        public FileVisitResult visitFileFailed(Path aFile, IOException aExc) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName().toString()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            throw aExc;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            return Runner.this.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if ("System Volume Information".equals((dir.getFileName()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            return Runner.this.preVisitDirectory(dir, attrs);
        }

    });

    if (myEvacuateCandidates.size() == 0) {
        myLog.info("No candidates for evacuation found");
    } else {
        StringBuilder sb = new StringBuilder("\nFound candidates for evacuation:");
        myEvacuateCandidates.keySet().forEach(p -> sb.append("\n    " + p.toString()));
        myLog.info(sb.toString());
    }

    if (myDryRun) {
        myLog.debug("DryRun flag is set. Doing nothing");
        return;
    }

    if (myFutures.size() > 0) {
        myLog.debug("Waiting for all async tasks to complete");
        CompletableFuture.allOf(myFutures.toArray(new CompletableFuture[myFutures.size()])).get();
    }

    if (myFailedChainPreparations.size() > 0) {
        for (Path path : myFailedChainPreparations.keySet()) {
            myLog.error("exception occured", myFailedChainPreparations.get(path));
        }

        throw new Exception("chain preparation failed. See above error messages");
    }

    for (Path src : myEvacuateCandidates.keySet()) {
        Path dst = myEvacuateCandidates.get(src);
        Path dstParent = dst.getParent();

        if (Files.notExists(dstParent)) {
            Files.createDirectories(dstParent); // FUTURE: overtake file attributes from src
        }

        if (myMove) {
            try {
                myLog.debug(
                        "Moving file system object \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
            } catch (AtomicMoveNotSupportedException e) {
                myLog.warn("Atomic move not supported. Try copy and then delete");

                if (Files.isDirectory(src)) {
                    myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                    FileUtils.copyDirectory(src.toFile(), dst.toFile());
                    myLog.debug("Delete folder \"" + src.toString() + "\"");
                    FileUtils.deleteDirectory(src.toFile());
                } else {
                    myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                    FileUtils.copyFile(src.toFile(), dst.toFile());
                    myLog.debug("Delete file \"" + src.toString() + "\"");
                    Files.delete(src);
                }
            }

        } else {
            if (Files.isDirectory(src)) {
                myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                FileUtils.copyDirectory(src.toFile(), dst.toFile());
            } else {
                myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                FileUtils.copyFile(src.toFile(), dst.toFile());
            }
        }
    }

    myLog.info("\nSuccessfully terminated." + "\n             Evacuated  Skipped" + "\n    Files  : "
            + StringUtils.leftPad("" + myEvacuationDirCount, 9)
            + StringUtils.leftPad("" + myExclusionDirCount, 9) + "\n    Folders: "
            + StringUtils.leftPad("" + myEvacuationFileCount, 9)
            + StringUtils.leftPad("" + myExclusionFileCount, 9));
}

From source file:org.cryptomator.frontend.webdav.servlet.DavFolder.java

private void moveInternal(DavNode destination) throws DavException {
    if (Files.isDirectory(destination.path.getParent())) {
        try {//  w w  w.  ja v a 2  s  .co  m
            Files.move(path, destination.path, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new DavException(DavServletResponse.SC_INTERNAL_SERVER_ERROR, e);
        }
    } else {
        throw new DavException(DavServletResponse.SC_CONFLICT, "Destination's parent doesn't exist.");
    }
}

From source file:com.interop.webapp.WebApp.java

@RequestMapping(value = "/image", method = RequestMethod.POST)
public String imageSave(Map<String, Object> model,
        @RequestParam(value = "imagename", defaultValue = "") String imageName,
        @RequestParam(value = "imagenew", defaultValue = "") String imageNew) {
    String user = getLoggedInUser();
    String filesRoot = config.getImageFilesRoot();
    if (!imageNew.equals("")) {
        // We have a new image from processing, need to replace the original.
        UserImageFileRepository store = new UserImageFileRepository(user, filesRoot);
        String destFilename = store.getPath(imageName);
        String srcFilename = filesRoot + '/' + processedFilesWebPath + '/'
                + imageNew.substring(imageNew.lastIndexOf('/') + 1);
        try {//from  w  w  w .  j ava 2 s .c om
            Files.move(Paths.get(URI.create(srcFilename)), Paths.get(URI.create(destFilename)),
                    REPLACE_EXISTING);
        } catch (Exception e) {
            log.error(String.format("Failed to copy [%s] to [%s] (%s)", srcFilename, destFilename,
                    e.getMessage()));
        }
    }
    return "redirect:/";
}