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(Path source, OutputStream out) throws IOException 

Source Link

Document

Copies all bytes from a file to an output stream.

Usage

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Before
public void createSymlinksScenario() throws IOException, URISyntaxException {
    Assume.assumeFalse(System.getProperty("os.name").toLowerCase().contains("windows"));

    /**//from  ww w.  ja  v  a2  s .  c  o  m
     * Creating following structure for test:
     *
     * $ROOT_PATH/newDir
     * $ROOT_PATH/newDir/page.html
     * $ROOT_PATH/newDir/innerDir/
     * $ROOT_PATH/newDir/innerDir/page.html
     * $ROOT_PATH/newSymlink -> $ROOT_PATH/newDir
     * $ROOT_PATH/newDir/innerSymlink -> $ROOT_PATH/newDir/innerDir/
     *
     */
    Path filePath = Paths.get(getClass().getResource("page.html").toURI());
    Path rootPath = filePath.getParent();

    Path newDir = rootPath.resolve("newDir");
    Files.createDirectories(newDir);

    Path innerDir = newDir.resolve("innerDir");
    Files.createDirectories(innerDir);

    Files.copy(filePath, newDir.resolve(filePath.getFileName()));
    Files.copy(filePath, innerDir.resolve(filePath.getFileName()));

    Path newSymlink = rootPath.resolve("newSymlink");

    Files.createSymbolicLink(newSymlink, newDir);

    Path innerSymlink = newDir.resolve("innerSymlink");

    Files.createSymbolicLink(innerSymlink, innerDir);
}

From source file:it.infn.ct.futuregateway.apiserver.storage.LocalStorage.java

@Override
public final void storeFile(final RESOURCE res, final String id, final InputStream input,
        final String destinationName, final String operation) throws IOException {

    Path filePath;/*www.  j a  v a 2 s  . c om*/
    if (operation != null && !operation.isEmpty()) {
        filePath = Paths.get(path, res.name().toLowerCase(), id, operation, destinationName);
    } else {
        filePath = Paths.get(path, res.name().toLowerCase(), id, destinationName);
    }

    Files.createDirectories(filePath.getParent());
    Files.deleteIfExists(filePath);
    Files.copy(input, filePath);
    log.debug("File " + destinationName + " written at '" + filePath + "'");
}

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

protected void downloadZip(String driverName, String url, File targetZip) {
    if (targetZip.exists()) {
        if (targetZip.length() > 0) {
            return;
        }/*from   w  ww .  jav a 2  s .  c  o m*/
        targetZip.delete();
    }

    System.out.printf("Downloading %s from %s...%n", driverName, url);

    File zipTemp = new File(targetZip.getAbsolutePath() + ".temp");
    zipTemp.getParentFile().mkdirs();

    try (InputStream input = URI.create(url).toURL().openStream()) {
        Files.copy(input, zipTemp.toPath());
    } catch (IOException e) {
        throw new IllegalStateException(
                "Unable to download " + driverName + " from " + url + " to " + targetZip, e);
    }

    if (!zipTemp.renameTo(targetZip)) {
        throw new IllegalStateException(String.format("Unable to rename %s to %s", zipTemp.getAbsolutePath(),
                targetZip.getAbsolutePath()));
    }
}

From source file:com.stratio.mojo.scala.crossbuild.RewriteJUnitXMLTest.java

@Test
public void idempotency() throws IOException {
    for (final String[] reportPair : reports) {
        final String resultReport = reportPair[1];
        final RewriteJUnitXML rewriter = new RewriteJUnitXML();
        tempDir.create();/*from   www  . j  av  a2s  .co m*/
        final File file = tempDir.newFile();
        file.delete();
        Files.copy(getClass().getResourceAsStream(resultReport), file.toPath());
        final String newBinaryVersion = "2.11";
        rewriter.rewrite(file, newBinaryVersion);
        assertEqualToResource(file, resultReport);
        file.delete();
    }
}

From source file:org.apache.geode.management.internal.cli.util.LogExporter.java

/**
 *
 * @return Path to the zip file that has all the filtered files, null if no files are selected to
 *         export.//  w w w.  j  a  v a2 s.com
 */
public Path export() throws IOException {
    Path tempDirectory = Files.createTempDirectory("exportLogs");

    if (baseLogFile != null) {
        for (Path logFile : findLogFiles(baseLogFile.toPath().getParent())) {
            Path filteredLogFile = tempDirectory.resolve(logFile.getFileName());
            writeFilteredLogFile(logFile, filteredLogFile);
        }
    }

    if (baseStatsFile != null) {
        for (Path statFile : findStatFiles(baseStatsFile.toPath().getParent())) {
            Files.copy(statFile, tempDirectory.resolve(statFile.getFileName()));
        }
    }

    Path zipFile = null;
    if (tempDirectory.toFile().listFiles().length > 0) {
        zipFile = Files.createTempFile("logExport", ".zip");
        ZipUtils.zipDirectory(tempDirectory, zipFile);
        LOGGER.info("Zipped files to: " + zipFile);
    }

    FileUtils.deleteDirectory(tempDirectory.toFile());

    return zipFile;
}

From source file:com.google.cloud.runtimes.builder.buildsteps.docker.StageDockerArtifactBuildStep.java

@Override
protected void doBuild(Path directory, Map<String, String> metadata) throws BuildStepException {
    try {//  ww  w.j  a  va 2  s  .  co  m
        // TODO wrap this in a try block and log a more friendly message if not found
        Path artifact = getArtifact(directory, metadata);
        logger.info("Found artifact {}", artifact);

        // make staging dir
        Path stagingDir = directory.resolve(DOCKER_STAGING_DIR);
        if (Files.exists(stagingDir)) {
            logger.info("Found a docker staging directory in provided sources. Cleaning {}",
                    stagingDir.toString());
            FileUtils.deleteDirectory(stagingDir.toFile());
        }
        Files.createDirectory(stagingDir);
        metadata.put(BuildStepMetadataConstants.DOCKER_STAGING_PATH, stagingDir.toString());

        logger.info("Preparing docker files in {}", stagingDir);

        // copy the artifact into the staging dir
        Files.copy(artifact, stagingDir.resolve(artifact.getFileName()));

        // copy the .dockerignore file into staging dir, if it exists
        Path dockerIgnoreFile = directory.resolve(DOCKER_IGNORE_FILE);
        if (Files.isRegularFile(dockerIgnoreFile)) {
            Files.copy(dockerIgnoreFile, stagingDir.resolve(DOCKER_IGNORE_FILE));
        }

        // Generate dockerfile
        String dockerfile = dockerfileGenerator.generateDockerfile(artifact.getFileName());
        Path dockerFileDest = stagingDir.resolve("Dockerfile");

        try (BufferedWriter writer = Files.newBufferedWriter(dockerFileDest, StandardCharsets.US_ASCII)) {
            writer.write(dockerfile);
        }
    } catch (IOException | ArtifactNotFoundException | TooManyArtifactsException e) {
        throw new BuildStepException(e);
    }
}

From source file:ru.mystamps.web.service.FilesystemImagePersistenceStrategy.java

protected void writeToFile(MultipartFile file, Path dest) throws IOException {
    // we can't use file.transferTo(dest) there because it creates file
    // relatively to directory from spring.http.multipart.location
    // in application.properties
    // See for details: https://jira.spring.io/browse/SPR-12650
    Files.copy(file.getInputStream(), dest);
}

From source file:com.surevine.gateway.scm.gatewayclient.GatewayPackage.java

void writeGZ(final Path gzPath, final Path tarPath) throws IOException, CompressorException {
    CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz",
            Files.newOutputStream(gzPath));

    try {/*from w  w w  . j  av  a  2 s .  c  o  m*/
        Files.copy(tarPath, cos);
    } finally {
        cos.close();
    }
}

From source file:com.stratio.mojo.scala.crossbuild.RewritePomTest.java

@Test
public void rewriteBaseArtifactId() throws IOException, XMLStreamException {
    final RewritePom rewritePom = new RewritePom();
    tempDir.create();/*from w ww  .j a va2  s .  c om*/
    final File file = tempDir.newFile();
    file.delete();
    Files.copy(getClass().getResourceAsStream("/basic_pom.xml"), file.toPath());
    final MavenProject project = getMockMavenProject(file);
    final String newBinaryVersion = "2.11";
    final String newVersion = "2.11.7";
    rewritePom.rewrite(project, "scala.binary.version", "scala.version", newBinaryVersion, newVersion);
    assertEqualToResource(file, "/basic_pom_result.xml");
    file.delete();
}

From source file:com.scooter1556.sms.server.utilities.DatabaseUtils.java

public static boolean createNewDatabaseFile(String db, int oldVersion, int newVersion) {
    if (SettingsService.getInstance().getDataDirectory() == null) {
        return false;
    }/*from   w  ww.j a  v  a2  s . c  o  m*/

    try {
        Path oldDb = Paths.get(SettingsService.getInstance().getDataDirectory() + "/db/" + db.toLowerCase()
                + "." + oldVersion + ".h2.db");
        Path newDb = Paths.get(SettingsService.getInstance().getDataDirectory() + "/db/" + db.toLowerCase()
                + "." + newVersion + ".h2.db");

        // Copy old database file to a new file and remove the old one
        Files.copy(oldDb, newDb);

        // Remove old database file
        return oldDb.toFile().delete();
    } catch (IOException ex) {
        return false;
    }
}