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:edu.mit.lib.bagit.Filler.java

/**
 * Adds the contents of the passed stream to the payload at the specified
 * relative path in the data directory tree.
 * //from  w  w w . j  av a 2  s  .  c  o m
 * @param relPath
 *            the relative path of the file
 * @param is
 *            the input stream to read.
 * @return Filler this Filler
 * @throws IOException
 */
public Filler payload(String relPath, InputStream is) throws IOException {
    if (dataFile(relPath).exists()) {

        // TODO: overwrite? or merge?

        // throw new
        // IllegalStateException("Payload file already exists at: "
        // + relPath);
    }
    // wrap stream in digest stream
    try (DigestInputStream dis = new DigestInputStream(is, MessageDigest.getInstance(csAlg))) {
        payloadSize += Files.copy(dis, dataFile(relPath).toPath());
        payloadCount++;
        // record checksum
        manWriter.writeLine(toHex(dis.getMessageDigest().digest()) + " " + DATA_PATH + relPath);
    } catch (NoSuchAlgorithmException nsaE) {
        throw new IOException("no algorithm: " + csAlg);
    }
    return this;
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.internal.actions.Explode.java

private void extract(ActionDescription aAction, Path aArchive, ArchiveInputStream aAStream, Path aTarget)
        throws IOException {
    // We always extract archives into a subfolder. Figure out the name of the folder.
    String base = getBase(aArchive.getFileName().toString());

    Map<String, Object> cfg = aAction.getConfiguration();
    int strip = cfg.containsKey("strip") ? (int) cfg.get("strip") : 0;

    AntFileFilter filter = new AntFileFilter(coerceToList(cfg.get("includes")),
            coerceToList(cfg.get("excludes")));

    ArchiveEntry entry = null;/*from  w  w w .ja  v  a 2s.  c o  m*/
    while ((entry = aAStream.getNextEntry()) != null) {
        String name = stripLeadingFolders(entry.getName(), strip);

        if (name == null) {
            // Stripped to null - nothing left to extract - continue;
            continue;
        }

        if (filter.accept(name)) {
            Path out = aTarget.resolve(base).resolve(name);
            if (entry.isDirectory()) {
                Files.createDirectories(out);
            } else {
                Files.createDirectories(out.getParent());
                Files.copy(aAStream, out);
            }
        }
    }
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

/** creates a plugin .zip and bad checksum file and returns the url for testing */
private String createPluginWithBadChecksum(final Path structure, String... properties) throws IOException {
    writeProperties(structure, properties);
    Path zip = createTempDir().resolve(structure.getFileName() + ".zip");
    try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) {
        Files.walkFileTree(structure, new SimpleFileVisitor<Path>() {
            @Override//from w  w  w  .  j a v a 2  s  . c  o  m
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                stream.putNextEntry(new ZipEntry(structure.relativize(file).toString()));
                Files.copy(file, stream);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    if (randomBoolean()) {
        writeSha1(zip, true);
    } else {
        writeMd5(zip, true);
    }
    return zip.toUri().toURL().toString();
}

From source file:com.liferay.sync.engine.SyncSystemTest.java

protected void addFile(Path testFilePath, JsonNode stepJsonNode) throws Exception {

    SyncSite syncSite = getSyncSite(stepJsonNode);

    String dependency = getString(stepJsonNode, "dependency");

    Path dependencyFilePath = getDependencyFilePath(testFilePath, dependency);

    FileSystem fileSystem = FileSystems.getDefault();

    dependency = getString(stepJsonNode, "target",
            dependency.replace("common" + fileSystem.getSeparator(), ""));

    Path targetFilePath = Paths.get(FileUtil.getFilePathName(syncSite.getFilePathName(), dependency));

    Files.copy(dependencyFilePath, targetFilePath);
}

From source file:com.linkedin.pinot.core.segment.index.converter.SegmentV1V2ToV3FormatConverter.java

private void copyCreationMetadata(File currentDir, File v3Dir) throws IOException {
    File v2CreationFile = new File(currentDir, V1Constants.SEGMENT_CREATION_META);
    File v3CreationFile = new File(v3Dir, V1Constants.SEGMENT_CREATION_META);
    Files.copy(v2CreationFile.toPath(), v3CreationFile.toPath());
}

From source file:edu.mit.lib.bagit.Loader.java

/**
 * Resolves a payload reference with passed stream content.
 * //from w  w  w.ja  va 2s  .c o  m
 * @param relPath
 *            the bag-relative path to the payload file
 * @param is
 *            the content input stream for payload
 * @throws IOException
 */
public void resolveRef(String relPath, InputStream is) throws IOException {
    // various checks - is ref known?
    if (!payloadRefMap.containsKey(relPath)) {
        throw new IOException("Unknown payload reference: " + relPath);
    }
    if (bagFile(relPath).exists()) {
        throw new IllegalStateException("Payload file already exists at: " + relPath);
    }
    // wrap stream in digest stream
    try (DigestInputStream dis = new DigestInputStream(is, MessageDigest.getInstance(csAlgorithm()))) {
        Files.copy(dis, bagFile(relPath).toPath());
        // record checksum
        manifestWriter().writeLine(toHex(dis.getMessageDigest().digest()) + " " + relPath);
        // remove from map
        payloadRefMap.remove(relPath);
    } catch (NoSuchAlgorithmException nsaE) {
        throw new IOException("no algorithm: " + csAlg);
    }
}

From source file:com.mweagle.tereus.commands.evaluation.common.LambdaUtils.java

protected void createStableZip(ZipOutputStream zipOS, Path parentDirectory, Path archiveRoot, MessageDigest md)
        throws IOException {
    // Sort & zip files
    final List<Path> childDirectories = new ArrayList<>();
    final List<Path> childFiles = new ArrayList<>();
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(parentDirectory);
    for (Path eachChild : dirStream) {
        if (Files.isDirectory(eachChild)) {
            childDirectories.add(eachChild);
        } else {/*from  www .  jav  a 2  s. com*/
            childFiles.add(eachChild);
        }
    }
    final int archiveRootLength = archiveRoot.toAbsolutePath().toString().length() + 1;
    childFiles.stream().sorted().forEach(eachPath -> {
        final String zeName = eachPath.toAbsolutePath().toString().substring(archiveRootLength);
        try {
            final ZipEntry ze = new ZipEntry(zeName);
            zipOS.putNextEntry(ze);
            Files.copy(eachPath, zipOS);
            md.update(Files.readAllBytes(eachPath));
            zipOS.closeEntry();
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    });

    childDirectories.stream().sorted().forEach(eachPath -> {
        try {
            createStableZip(zipOS, eachPath, archiveRoot, md);
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    });
}

From source file:org.apache.karaf.tooling.ArchiveMojo.java

private void addFileToTarGz(TarArchiveOutputStream tOut, Path f, String base) throws IOException {
    if (Files.isDirectory(f)) {
        String entryName = base + f.getFileName().toString() + "/";
        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
        tOut.putArchiveEntry(tarEntry);//from ww  w.j av  a 2 s .c  o m
        tOut.closeArchiveEntry();
        try (DirectoryStream<Path> children = Files.newDirectoryStream(f)) {
            for (Path child : children) {
                addFileToTarGz(tOut, child, entryName);
            }
        }
    } else if (useSymLinks && Files.isSymbolicLink(f)) {
        String entryName = base + f.getFileName().toString();
        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName, TarConstants.LF_SYMLINK);
        tarEntry.setLinkName(Files.readSymbolicLink(f).toString());
        tOut.putArchiveEntry(tarEntry);
        tOut.closeArchiveEntry();
    } else {
        String entryName = base + f.getFileName().toString();
        TarArchiveEntry tarEntry = new TarArchiveEntry(entryName);
        tarEntry.setSize(Files.size(f));
        if (entryName.contains("/bin/") || (!usePathPrefix && entryName.startsWith("bin/"))) {
            if (entryName.endsWith(".bat")) {
                tarEntry.setMode(0644);
            } else {
                tarEntry.setMode(0755);
            }
        }
        tOut.putArchiveEntry(tarEntry);
        Files.copy(f, tOut);
        tOut.closeArchiveEntry();
    }
}

From source file:im.bci.gamesitekit.GameSiteKitMain.java

private void copyPhp() throws IOException {
    Files.copy(templateDir.resolve("lang_selector.php"), outputDir.resolve("index.php"));
}

From source file:onl.area51.filesystem.ftp.client.FTPClient.java

/**
 * Store a Path to the remote server//w  ww  . j a v a  2 s .  c o m
 * <p>
 * @param remote
 * @param target
 *               <p>
 * @throws IOException
 */
default void store(String remote, Path target) throws IOException {
    try (OutputStream os = storeOutputStream(remote)) {
        Files.copy(target, os);
    } finally {
        completePendingCommand();
    }
}