Example usage for java.nio.file Files copy

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

Introduction

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

Prototype

public static long copy(InputStream in, Path target, CopyOption... options) throws IOException 

Source Link

Document

Copies all bytes from an input stream to a file.

Usage

From source file:org.apache.hadoop.yarn.server.nodemanager.TestLinuxContainerExecutorWithMocks.java

private void setupMockExecutor(String executorPath, Configuration conf) throws IOException {
    //we'll always use the tmpMockExecutor - since
    // PrivilegedOperationExecutor can only be initialized once.

    Files.copy(Paths.get(executorPath), Paths.get(tmpMockExecutor), REPLACE_EXISTING);

    File executor = new File(tmpMockExecutor);

    if (!FileUtil.canExecute(executor)) {
        FileUtil.setExecutable(executor, true);
    }//from   ww w  . j  a  v a2  s  . c o m
    String executorAbsolutePath = executor.getAbsolutePath();
    conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorAbsolutePath);
}

From source file:org.fao.geonet.utils.XmlRequest.java

protected final Path doExecuteLarge(HttpRequestBase httpMethod, Path outFile) throws IOException {

    try (ClientHttpResponse httpResponse = doExecute(httpMethod)) {
        Files.copy(httpResponse.getBody(), outFile, StandardCopyOption.REPLACE_EXISTING);
        return outFile;
    } finally {/*from  w  w  w  . j av  a  2  s  .co  m*/
        httpMethod.releaseConnection();

        sentData = getSentData(httpMethod);
        //--- we do not save received data because it can be very large
    }
}

From source file:BluemixUtils.java

private static void copyPhotosInTempDir(List<ClassifierUnit> all, int minSize) throws IOException {
    for (ClassifierUnit unit : all) {
        File dir = new File(TMP_DIR + File.separator + unit.getName());
        dir.mkdir();//from w w w . j a  v a2 s  .  c om
        System.out.println("Copying files to " + dir.getAbsolutePath());
        File photosDir = new File(unit.getFolderWithImages());
        File[] photoes = photosDir.listFiles(filter);
        for (int i = 0; i < minSize; i++) {
            File source = photoes[i];
            System.out.println("Copying file " + photoes[i].getName());
            Files.copy(source.toPath(),
                    (new File(dir.getAbsolutePath() + File.separator + (i + 1)
                            + source.getName().substring(source.getName().indexOf(".")))).toPath(),
                    StandardCopyOption.REPLACE_EXISTING);
        }

    }
}

From source file:edu.harvard.iq.dataverse.dataaccess.DataFileIO.java

public void copyPath(Path fileSystemPath) throws IOException {
    long newFileSize = -1;
    // if this is a local fileystem file, we'll use a 
    // quick Files.copy method: 
    if (isLocalFile()) {
        Path outputPath = null;/* ww w .  j  a v a 2s  .c  o m*/
        try {
            outputPath = getFileSystemPath();
        } catch (IOException ex) {
            outputPath = null;
        }
        if (outputPath != null) {
            Files.copy(fileSystemPath, outputPath, StandardCopyOption.REPLACE_EXISTING);
            newFileSize = outputPath.toFile().length();
        }

    } else {
        // otherwise we'll open a writable byte channel and 
        // copy the source file bytes using Channel.transferTo():

        WritableByteChannel writeChannel = null;
        FileChannel readChannel = null;
        String failureMsg = null;

        try {

            open(DataAccessOption.WRITE_ACCESS);
            writeChannel = getWriteChannel();
            readChannel = new FileInputStream(fileSystemPath.toFile()).getChannel();

            long bytesPerIteration = 16 * 1024; // 16K bytes
            long start = 0;
            while (start < readChannel.size()) {
                readChannel.transferTo(start, bytesPerIteration, writeChannel);
                start += bytesPerIteration;
            }
            newFileSize = readChannel.size();

        } catch (IOException ioex) {
            failureMsg = ioex.getMessage();
            if (failureMsg == null) {
                failureMsg = "Unknown exception occured.";
            }
        } finally {
            if (readChannel != null) {
                try {
                    readChannel.close();
                } catch (IOException e) {
                }
            }
            if (writeChannel != null) {
                try {
                    writeChannel.close();
                } catch (IOException e) {
                }
            }
        }

        if (failureMsg != null) {
            throw new IOException(failureMsg);
        }
    }

    // if it has worked successfully, we also need to reset the size
    // of the object. 
    setSize(newFileSize);
}

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  www .j a v  a 2s.c o  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:media_organizer.MediaInspector.java

@SuppressWarnings("unchecked")
public void unique_file_generator() {
    Iterator<File> iter = FileUtils.iterateFilesAndDirs(topStartDirectory.toFile(), TrueFileFilter.INSTANCE,
            new IOFileFilter() {
                @Override//  w ww  .j  a v  a 2  s . co m
                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.ethlo.geodata.util.ResourceUtil.java

private Entry<Date, File> downloadIfNewer(DataType dataType, Resource resource, CheckedFunction<Path, Path> fun)
        throws IOException {
    publisher.publishEvent(new DataLoadedEvent(this, dataType, Operation.DOWNLOAD, 0, 1));
    final String alias = dataType.name().toLowerCase();
    final File tmpDownloadedFile = new File(tmpDir, alias);
    final Date remoteLastModified = new Date(resource.lastModified());
    final long localLastModified = tmpDownloadedFile.exists() ? tmpDownloadedFile.lastModified() : -2;
    logger.info(//from w  ww .  j ava  2s . c  o m
            "Local file for alias {}" + "\nPath: {}" + "\nExists: {}" + "\nLocal last-modified: {} "
                    + "\nRemote last modified: {}",
            alias, tmpDownloadedFile.getAbsolutePath(), tmpDownloadedFile.exists(),
            formatDate(localLastModified), formatDate(remoteLastModified.getTime()));

    if (!tmpDownloadedFile.exists() || remoteLastModified.getTime() > localLastModified) {
        logger.info("Downloading {}", resource.getURL());
        Files.copy(resource.getInputStream(), tmpDownloadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        logger.info("Download complete");
    }

    final Path preppedFile = fun.apply(tmpDownloadedFile.toPath());
    Files.setLastModifiedTime(tmpDownloadedFile.toPath(), FileTime.fromMillis(remoteLastModified.getTime()));
    Files.setLastModifiedTime(preppedFile, FileTime.fromMillis(remoteLastModified.getTime()));
    publisher.publishEvent(new DataLoadedEvent(this, dataType, Operation.DOWNLOAD, 1, 1));
    return new AbstractMap.SimpleEntry<>(new Date(remoteLastModified.getTime()), preppedFile.toFile());
}

From source file:dialog.DialogFunctionUser.java

private void actionEditUserNoController() {
    if (!isValidData()) {
        return;//w  w  w.ja v  a 2s.c o  m
    }
    tfUsername.setEditable(false);
    String username = tfUsername.getText();
    String fullname = tfFullname.getText();
    String password = mUser.getPassword();
    if (tfPassword.getPassword().length == 0) {
        password = new String(tfPassword.getPassword());
        password = LibraryString.md5(password);
    }
    int role = cbRole.getSelectedIndex();
    User objUser;
    if (mAvatar != null) {
        objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mAvatar.getPath());
        if ((new ModelUser()).editItem(objUser)) {
            String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(mAvatar.getName());
            Path source = Paths.get(mAvatar.toURI());
            Path destination = Paths.get("files/" + fileName);
            Path pathOldAvatar = Paths.get(mUser.getAvatar());
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                Files.deleteIfExists(pathOldAvatar);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    } else {
        objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mUser.getAvatar());
        if (mControllerUser.editItem(objUser, mRow)) {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
    mUser = objUser;
    this.dispose();
}

From source file:net.codestory.simplelenium.driver.Downloader.java

protected void untar(File tar, File toDir) throws IOException {
    try (FileInputStream fin = new FileInputStream(tar);
            BufferedInputStream bin = new BufferedInputStream(fin);
            TarArchiveInputStream tarInput = new TarArchiveInputStream(bin)) {
        ArchiveEntry entry;/*  w ww . ja v  a2 s  .c om*/
        while (null != (entry = tarInput.getNextTarEntry())) {
            if (entry.isDirectory()) {
                continue;
            }

            File to = new File(toDir, entry.getName());

            File parent = to.getParentFile();
            if (!parent.exists()) {
                if (!parent.mkdirs()) {
                    throw new IOException("Unable to create folder " + parent);
                }
            }

            Files.copy(tarInput, to.toPath(), REPLACE_EXISTING);
        }
    }
}

From source file:org.osiam.OsiamHome.java

private void copyToHome(Resource resource, Path osiamHomeDir) throws IOException {
    String pathUnderHome = resource.getURL().toString().replaceFirst(".*home/", "");
    Path target = osiamHomeDir.resolve(pathUnderHome);
    Files.createDirectories(target.getParent());
    Files.copy(resource.getInputStream(), target, StandardCopyOption.REPLACE_EXISTING);
}