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:com.github.thorqin.toolkit.web.utility.UploadManager.java

public void copyTo(String fileId, File destPath, boolean replaceExisting) throws IOException {
    String filePath = fileIdToPath(fileId);
    File dataFile = new File(filePath + ".data");
    File parentFile = destPath.getParentFile();
    if (parentFile != null)
        Files.createDirectories(parentFile.toPath());
    if (replaceExisting)
        Files.copy(dataFile.toPath(), destPath.toPath(), StandardCopyOption.REPLACE_EXISTING);
    else/*from   w w  w  .  j av a2 s .c  o  m*/
        Files.copy(dataFile.toPath(), destPath.toPath());
}

From source file:net.wouterdanes.docker.maven.AbstractDockerMojo.java

protected void cleanUpStartedContainers() throws MojoExecutionException {
    Optional<Path> logsDir = Optional.ofNullable(stripToNull(logs)).map(this::getLogDirectory);
    if (logsDir.isPresent()) {
        getLog().info("Writing docker container logs to directory: " + logsDir.get());
    } else {//from w  w w.  j  ava2s .c o  m
        getLog().info("NOT writing docker container logs.");
    }

    List<String> stoppedContainerIds = new ArrayList<>();
    for (Iterator<StartedContainerInfo> it = getStartedContainers().iterator(); it.hasNext();) {
        StartedContainerInfo startedContainerInfo = it.next();
        String containerId = startedContainerInfo.getContainerInfo().getId();
        String containerName = startedContainerInfo.getContainerId();
        getLog().info(String.format("Stopping container '%s'..", containerId));
        try {
            if (logsDir.isPresent()) {
                Path logFile = logsDir.get().resolve(containerName + ".log");
                getLog().info("Writing logs to: " + logFile);
                String logs = getDockerProvider().getLogs(containerId);

                try {
                    Files.copy(new ByteArrayInputStream(logs.getBytes()), logFile, REPLACE_EXISTING);
                } catch (IOException e) {
                    if (getLog().isDebugEnabled()) {
                        getLog().error("Failed to write docker logs to: " + logFile, e);
                    } else {
                        getLog().error("Failed to write docker logs to: " + logFile);
                    }
                }
            }

            getDockerProvider().stopContainer(containerId);
            it.remove();
            stoppedContainerIds.add(containerId);
        } catch (DockerException e) {
            getLog().error("Failed to stop container (this means it also won't be deleted)", e);
        }
    }

    if (!keepContainers) {
        for (String containerId : stoppedContainerIds) {
            getLog().info(String.format("Deleting container '%s'..", containerId));
            try {
                getDockerProvider().deleteContainer(containerId);
            } catch (DockerException e) {
                getLog().error("Failed to delete container", e);
            }
        }
    }
}

From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java

private void moveOrCopyFile(File originNodeFile, File targetNodeFile) throws IOException {
    try {//  w w  w .  j ava2  s  .  c o m
        Files.move(originNodeFile.toPath(), targetNodeFile.toPath(), StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.ATOMIC_MOVE);
    } catch (AtomicMoveNotSupportedException amnse) {
        logger.warn(
                "Could not perform atomic move: " + amnse.getMessage() + ". Trying regular copy and delete...");
        Files.copy(originNodeFile.toPath(), targetNodeFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        deleteFile(originNodeFile);
    }
}

From source file:com.bekwam.resignator.commands.UnsignCommand.java

public void copyJAR(String sourceJarFileName, String targetJarFileName) throws CommandExecutionException {

    Path sourceJarFile = Paths.get(sourceJarFileName);
    Path targetJarFile = Paths.get(targetJarFileName);

    try {/*w  ww.j  ava  2s  .co  m*/

        Files.copy(sourceJarFile, targetJarFile, StandardCopyOption.REPLACE_EXISTING);

    } catch (IOException exc) {
        String msg = String.format("can't copy %s to %s", sourceJarFileName, targetJarFileName);
        logger.error(msg, exc);
        throw new CommandExecutionException(msg);
    }
}

From source file:com.amazon.alexa.avs.AVSAudioPlayer.java

public void handlePlay(Play play) throws DirectiveHandlingException {
    AudioItem item = play.getAudioItem();
    if (play.getPlayBehavior() == Play.PlayBehavior.REPLACE_ALL) {
        clearAll();//w  ww .  j a  v a2s.co m
    } else if (play.getPlayBehavior() == Play.PlayBehavior.REPLACE_ENQUEUED) {
        clearEnqueued();
    }

    Stream stream = item.getStream();
    String streamUrl = stream.getUrl();
    String streamId = stream.getToken();
    long offset = stream.getOffsetInMilliseconds();
    log.info("URL: {}", streamUrl);
    log.info("StreamId: {}", streamId);
    log.info("Offset: {}", offset);

    if (stream.hasAttachedContent()) {
        try {
            File tmp = File.createTempFile(UUID.randomUUID().toString(), ".mp3");
            tmp.deleteOnExit();
            Files.copy(stream.getAttachedContent(), tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);

            stream.setUrl(tmp.getAbsolutePath());
            add(stream);
        } catch (IOException e) {
            log.error("Error while saving audio to a file", e);
            throw new DirectiveHandlingException(ExceptionType.INTERNAL_ERROR,
                    "Error saving attached content to disk, unable to handle Play directive.");
        }
    } else {
        add(stream);
    }
}

From source file:com.vasquez.FileSwitcher.java

private void backupFilesHandler(File source, File dest) {
    Path sourceDll = Paths.get(source.getAbsolutePath());
    Path destDll = Paths.get(dest.getAbsolutePath());

    // Check to see if the version is 1.00/1.07 and if it is then don't copy some files
    try {/*ww  w .  ja  v a  2s  . c  o m*/
        // Expansion
        if (expansion) {
            if (version.equalsIgnoreCase("1.07") && !source.getName().equalsIgnoreCase("Patch_D2.mpq")) {
                Files.copy(sourceDll, destDll, REPLACE_EXISTING);
            } else if (version.equalsIgnoreCase("1.07") && source.getName().equalsIgnoreCase("Patch_D2.mpq")) {
                source.delete();
            } else {
                // You can copy the same files for all the other versions (Well... anything > 1.07).
                Files.copy(sourceDll, destDll, REPLACE_EXISTING);
            }
        } else {
            // Classic
            if (version.equalsIgnoreCase("1.00") && (!source.getName().equalsIgnoreCase("Patch_D2.mpq")
                    && !source.getName().equalsIgnoreCase("BNUpdate.exe"))) {
                Files.copy(sourceDll, destDll, REPLACE_EXISTING);
            } else if (version.equalsIgnoreCase("1.00") && (source.getName().equalsIgnoreCase("Patch_D2.mpq")
                    || source.getName().equalsIgnoreCase("BNUpdate.exe"))) {
                source.delete();
            } else {
                // You can copy the same files for all the other versions (Well... anything > 1.00).
                Files.copy(sourceDll, destDll, REPLACE_EXISTING);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.book.identification.rest.VolumeResource.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)/*from ww w .ja  v a  2s  . c o m*/
@Path("upload/")
public Response upload(@FormDataParam("file") InputStream inputStream) throws Exception {
    //Save in temporal file
    File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".temp");
    FileUtils.copyInputStreamToFile(inputStream, tempFile);

    String md5Hex = DigestUtils.md5Hex(FileUtils.openInputStream(tempFile));

    java.nio.file.Path path = new File(System.getProperty("user.dir")).toPath().resolve("books");
    if (!Files.exists(path)) {
        Files.createDirectories(path);
    }
    java.nio.file.Path filePath = path.resolve(md5Hex);

    try {
        Files.copy(tempFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        return Response.serverError().build();
    }
    return Response.ok(md5Hex).build();

}

From source file:org.apache.drill.yarn.core.TestConfig.java

private DoYTestConfig initConfig(String configName) throws IOException, DoyConfigException {
    File tempDir = new File(System.getProperty("java.io.tmpdir"));
    File configDir = new File(tempDir, "config");
    if (configDir.exists()) {
        FileUtils.forceDelete(configDir);
    }/*from  w  ww  . ja v a 2 s  .c o  m*/
    configDir.mkdirs();
    configDir.deleteOnExit();

    InputStream in = getClass().getResourceAsStream("/" + configName);
    File dest = new File(configDir, "drill-on-yarn.conf");
    Files.copy(in, dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
    in = getClass().getResourceAsStream("/test-doy-distrib.conf");
    dest = new File(configDir, "doy-distrib.conf");
    Files.copy(in, dest.toPath(), StandardCopyOption.REPLACE_EXISTING);

    System.setProperty(DrillOnYarnConfig.YARN_QUEUE, "sys-queue");

    TestClassLoader cl = new TestClassLoader(this.getClass().getClassLoader(), configDir);

    assertNotNull(cl.getResource(DrillOnYarnConfig.DISTRIB_FILE_NAME));

    return new DoYTestConfig(cl, configDir);
}

From source file:com.yahoo.parsec.gradle.utils.FileUtils.java

/**
 * Un-TarZip a tgz file.//  w w w  .jav  a2 s.  c  o  m
 *
 * @param resourcePath resource path
 * @param outputPath   output path
 * @param overwrite    overwrite flag
 * @throws IOException IOException
 */
public void unTarZip(String resourcePath, String outputPath, boolean overwrite) throws IOException {
    try (InputStream inputStream = getClass().getResourceAsStream(resourcePath);
            GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(inputStream);
            TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(
                    gzipCompressorInputStream);) {
        TarArchiveEntry tarArchiveEntry;
        logger.info("Extracting tgz file to " + outputPath);

        while ((tarArchiveEntry = tarArchiveInputStream.getNextTarEntry()) != null) {
            final File outputFile = new File(outputPath, tarArchiveEntry.getName());

            if (!overwrite && outputFile.exists()) {
                continue;
            }

            if (tarArchiveEntry.isDirectory()) {
                outputFile.mkdirs();
            } else {
                Files.copy(tarArchiveInputStream, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        }
    } catch (IOException e) {
        throw e;
    }
}

From source file:divconq.tool.Updater.java

static public boolean tryUpdate() {
    @SuppressWarnings("resource")
    final Scanner scan = new Scanner(System.in);

    FuncResult<RecordStruct> ldres = Updater.loadDeployed();

    if (ldres.hasErrors()) {
        System.out.println("Error reading deployed.json file: " + ldres.getMessage());
        return false;
    }/*ww w. j  a v a  2  s  . c om*/

    RecordStruct deployed = ldres.getResult();

    String ver = deployed.getFieldAsString("Version");
    String packfolder = deployed.getFieldAsString("PackageFolder");
    String packprefix = deployed.getFieldAsString("PackagePrefix");

    if (StringUtil.isEmpty(ver) || StringUtil.isEmpty(packfolder)) {
        System.out.println("Error reading deployed.json file: Missing Version or PackageFolder");
        return false;
    }

    if (StringUtil.isEmpty(packprefix))
        packprefix = "DivConq";

    System.out.println("Current Version: " + ver);

    Path packpath = Paths.get(packfolder);

    if (!Files.exists(packpath) || !Files.isDirectory(packpath)) {
        System.out.println("Error reading PackageFolder - it may not exist or is not a folder.");
        return false;
    }

    File pp = packpath.toFile();
    RecordStruct deployment = null;
    File matchpack = null;

    for (File f : pp.listFiles()) {
        if (!f.getName().startsWith(packprefix + "-") || !f.getName().endsWith("-bin.zip"))
            continue;

        System.out.println("Checking: " + f.getName());

        // if not a match before, clear this
        deployment = null;

        try {
            ZipFile zf = new ZipFile(f);

            Enumeration<ZipArchiveEntry> entries = zf.getEntries();

            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();

                if (entry.getName().equals("deployment.json")) {
                    //System.out.println("crc: " + entry.getCrc());

                    FuncResult<CompositeStruct> pres = CompositeParser.parseJson(zf.getInputStream(entry));

                    if (pres.hasErrors()) {
                        System.out.println("Error reading deployment.json file");
                        break;
                    }

                    deployment = (RecordStruct) pres.getResult();

                    break;
                }
            }

            zf.close();
        } catch (IOException x) {
            System.out.println("Error reading deployment.json file: " + x);
        }

        if (deployment != null) {
            String fndver = deployment.getFieldAsString("Version");
            String fnddependson = deployment.getFieldAsString("DependsOn");

            if (ver.equals(fnddependson)) {
                System.out.println("Found update: " + fndver);
                matchpack = f;
                break;
            }
        }
    }

    if ((matchpack == null) || (deployment == null)) {
        System.out.println("No updates found!");
        return false;
    }

    String fndver = deployment.getFieldAsString("Version");
    String umsg = deployment.getFieldAsString("UpdateMessage");

    if (StringUtil.isNotEmpty(umsg)) {
        System.out.println("========================================================================");
        System.out.println(umsg);
        System.out.println("========================================================================");
    }

    System.out.println();
    System.out.println("Do you want to install?  (y/n)");
    System.out.println();

    String p = scan.nextLine().toLowerCase();

    if (!p.equals("y"))
        return false;

    System.out.println();

    System.out.println("Intalling: " + fndver);

    Set<String> ignorepaths = new HashSet<>();

    ListStruct iplist = deployment.getFieldAsList("IgnorePaths");

    if (iplist != null) {
        for (Struct df : iplist.getItems())
            ignorepaths.add(df.toString());
    }

    ListStruct dflist = deployment.getFieldAsList("DeleteFiles");

    // deleting
    if (dflist != null) {
        for (Struct df : dflist.getItems()) {
            Path delpath = Paths.get(".", df.toString());

            if (Files.exists(delpath)) {
                System.out.println("Deleting: " + delpath.toAbsolutePath());

                try {
                    Files.delete(delpath);
                } catch (IOException x) {
                    System.out.println("Unable to Delete: " + x);
                }
            }
        }
    }

    // copying updates

    System.out.println("Checking for updated files: ");

    try {
        @SuppressWarnings("resource")
        ZipFile zf = new ZipFile(matchpack);

        Enumeration<ZipArchiveEntry> entries = zf.getEntries();

        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            String entryname = entry.getName().replace('\\', '/');
            boolean xfnd = false;

            for (String exculde : ignorepaths)
                if (entryname.startsWith(exculde)) {
                    xfnd = true;
                    break;
                }

            if (xfnd)
                continue;

            System.out.print(".");

            Path localpath = Paths.get(".", entryname);

            if (entry.isDirectory()) {
                if (!Files.exists(localpath))
                    Files.createDirectories(localpath);
            } else {
                boolean hashmatch = false;

                if (Files.exists(localpath)) {
                    String local = null;
                    String update = null;

                    try (InputStream lin = Files.newInputStream(localpath)) {
                        local = HashUtil.getMd5(lin);
                    }

                    try (InputStream uin = zf.getInputStream(entry)) {
                        update = HashUtil.getMd5(uin);
                    }

                    hashmatch = (StringUtil.isNotEmpty(local) && StringUtil.isNotEmpty(update)
                            && local.equals(update));
                }

                if (!hashmatch) {
                    System.out.print("[" + entryname + "]");

                    try (InputStream uin = zf.getInputStream(entry)) {
                        Files.createDirectories(localpath.getParent());

                        Files.copy(uin, localpath, StandardCopyOption.REPLACE_EXISTING);
                    } catch (Exception x) {
                        System.out.println("Error updating: " + entryname + " - " + x);
                        return false;
                    }
                }
            }
        }

        zf.close();
    } catch (IOException x) {
        System.out.println("Error reading update package: " + x);
    }

    // updating local config
    deployed.setField("Version", fndver);

    OperationResult svres = Updater.saveDeployed(deployed);

    if (svres.hasErrors()) {
        System.out.println("Intalled: " + fndver
                + " but could not update deployed.json.  Repair the file before continuing.\nError: "
                + svres.getMessage());
        return false;
    }

    System.out.println("Intalled: " + fndver);

    return true;
}