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.google.devtools.build.lib.bazel.repository.TarGzFunction.java

@Nullable
@Override/*from  w w  w  .  j  a  v  a 2 s.c  om*/
public SkyValue compute(SkyKey skyKey, Environment env) throws RepositoryFunctionException {
    DecompressorDescriptor descriptor = (DecompressorDescriptor) skyKey.argument();
    Optional<String> prefix = descriptor.prefix();
    boolean foundPrefix = false;

    try (GZIPInputStream gzipStream = new GZIPInputStream(
            new FileInputStream(descriptor.archivePath().getPathFile()))) {
        TarArchiveInputStream tarStream = new TarArchiveInputStream(gzipStream);
        TarArchiveEntry entry;
        while ((entry = tarStream.getNextTarEntry()) != null) {
            StripPrefixedPath entryPath = StripPrefixedPath.maybeDeprefix(entry.getName(), prefix);
            foundPrefix = foundPrefix || entryPath.foundPrefix();
            if (entryPath.skip()) {
                continue;
            }

            Path filename = descriptor.repositoryPath().getRelative(entryPath.getPathFragment());
            FileSystemUtils.createDirectoryAndParents(filename.getParentDirectory());
            if (entry.isDirectory()) {
                FileSystemUtils.createDirectoryAndParents(filename);
            } else {
                if (entry.isSymbolicLink()) {
                    PathFragment linkName = new PathFragment(entry.getLinkName());
                    if (linkName.isAbsolute()) {
                        linkName = linkName.relativeTo(PathFragment.ROOT_DIR);
                        linkName = descriptor.repositoryPath().getRelative(linkName).asFragment();
                    }
                    FileSystemUtils.ensureSymbolicLink(filename, linkName);
                } else {
                    Files.copy(tarStream, filename.getPathFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
                    filename.chmod(entry.getMode());
                }
            }
        }
    } catch (IOException e) {
        throw new RepositoryFunctionException(e, Transience.TRANSIENT);
    }

    if (prefix.isPresent() && !foundPrefix) {
        throw new RepositoryFunctionException(
                new IOException("Prefix " + prefix.get() + " was given, but not found in the archive"),
                Transience.PERSISTENT);
    }

    return new DecompressorValue(descriptor.repositoryPath());
}

From source file:org.apache.druid.indexer.HdfsClasspathSetupTest.java

@Before
public void setUp() throws IOException {
    // intermedatePath and finalClasspath are relative to hdfsTmpDir directory.
    intermediatePath = new Path(StringUtils.format("/tmp/classpath/%s", UUIDUtils.generateUuid()));
    finalClasspath = new Path(StringUtils.format("/tmp/intermediate/%s", UUIDUtils.generateUuid()));
    dummyJarFile = tempFolder.newFile("dummy-test.jar");
    Files.copy(new ByteArrayInputStream(StringUtils.toUtf8(dummyJarString)), dummyJarFile.toPath(),
            StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.castlemock.web.basis.manager.FileManager.java

public List<File> uploadFiles(final String downloadURL) throws IOException {
    final File fileDirectory = new File(tempFilesFolder);

    if (!fileDirectory.exists()) {
        fileDirectory.mkdirs();/*from   w  ww .  j  a  v  a2 s.c o  m*/
    }

    final URL url = new URL(downloadURL);
    final String fileName = generateNewFileName();
    final File file = new File(fileDirectory.getAbsolutePath() + File.separator + fileName);

    if (!file.exists()) {
        file.createNewFile();
    }

    final Path targetPath = file.toPath();
    Files.copy(url.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
    final List<File> files = new ArrayList<>();
    files.add(file);
    return files;
}

From source file:com.github.podd.resources.test.DataReferenceAttachResourceImplTest.java

/**
 * Given the path to a resource containing an incomplete File Reference object, this method
 * constructs a complete File Reference and returns it as an RDF/XML string.
 *
 * @param fragmentSource/* ww  w  .  j a  va2s .  c o m*/
 *            Location of resource containing incomplete File Reference
 * @return String containing RDF statements
 */
private String buildFileReferenceString(final String fragmentSource, final RDFFormat format,
        final Path testDirectory) throws Exception {
    // read the fragment's RDF statements into a Model
    final InputStream inputStream = this.getClass().getResourceAsStream(fragmentSource);
    final Model model = Rio.parse(inputStream, "", format);

    // path to be set as part of the file reference
    final Path completePath = testDirectory.resolve(TestConstants.TEST_REMOTE_FILE_NAME);
    Files.copy(
            this.getClass().getResourceAsStream(
                    TestConstants.TEST_REMOTE_FILE_PATH + "/" + TestConstants.TEST_REMOTE_FILE_NAME),
            completePath, StandardCopyOption.REPLACE_EXISTING);

    final Resource aliasUri = model.filter(null, PODD.PODD_BASE_HAS_ALIAS, null).subjects().iterator().next();
    model.add(aliasUri, PODD.PODD_BASE_HAS_FILE_PATH,
            ValueFactoryImpl.getInstance().createLiteral(testDirectory.toAbsolutePath().toString()));
    model.add(aliasUri, PODD.PODD_BASE_HAS_FILENAME,
            ValueFactoryImpl.getInstance().createLiteral(TestConstants.TEST_REMOTE_FILE_NAME));

    // get a String representation of the statements in the Model
    final StringWriter out = new StringWriter();
    Rio.write(model, out, format);

    return out.toString();
}

From source file:net.certiv.antlr.project.util.Utils.java

/**
 * Move all files from the source directory to the destination directory.
 * //from w w  w .  j  a  va 2s  . c om
 * @param source
 *            the source directory
 * @param dest
 *            the destination directory
 * @return
 * @throws IOException
 */
public static boolean moveAllFiles(File source, File dest) throws IOException {
    if (source == null || dest == null)
        throw new IllegalArgumentException("Directory cannot be null");
    if (!source.exists() || !source.isDirectory())
        throw new IOException("Source directory must exist: " + source.getCanonicalPath());

    dest.mkdirs();
    if (!dest.exists() || !dest.isDirectory())
        throw new IOException("Destination directory must exist: " + dest.getCanonicalPath());

    Path srcDir = source.toPath();
    Path dstDir = dest.toPath();
    DirectoryStream<Path> ds = Files.newDirectoryStream(srcDir);
    int tot = 0;
    for (Path src : ds) {
        Files.copy(src, dstDir.resolve(src.getFileName()), REPLACE_EXISTING);
        tot++;
    }
    Log.info(Utils.class, "Moved " + tot + " files");
    return false;
}

From source file:com.geewhiz.pacify.utils.FileUtils.java

public static void copyDirectory(File sourceDir, File targetDir) throws IOException {
    if (sourceDir.isDirectory()) {
        copyDirectoryRecursively(sourceDir.getAbsoluteFile(), targetDir.getAbsoluteFile());
    } else {/*from w  ww  . ja  va2s  . c  o  m*/
        Files.copy(sourceDir.getAbsoluteFile().toPath(), targetDir.getAbsoluteFile().toPath(),
                java.nio.file.StandardCopyOption.COPY_ATTRIBUTES);
    }
}

From source file:com.hpe.caf.worker.testing.preparation.PreparationResultProcessor.java

protected Path saveContentFile(TestItem<TInput, TExpected> testItem, String baseFileName, String extension,
        InputStream dataStream) throws IOException {
    String outputFolder = getOutputFolder();
    if (configuration.isStoreTestCaseWithInput()) {

        Path path = Paths.get(testItem.getInputData().getInputFile()).getParent();
        outputFolder = Paths.get(configuration.getTestDataFolder(), path == null ? "" : path.toString())
                .toString();/*from  www. ja  v  a  2s  . co  m*/
    }

    baseFileName = FilenameUtils.normalize(baseFileName);
    baseFileName = Paths.get(baseFileName).getFileName().toString();
    Path contentFile = Paths.get(outputFolder, baseFileName + "." + extension + ".content");
    Files.deleteIfExists(contentFile);
    Files.copy(dataStream, contentFile, REPLACE_EXISTING);

    return getRelativeLocation(contentFile);
}

From source file:de.fabianonline.telegram_backup.mediafilemanager.StickerFileManager.java

public void download() throws RpcErrorException, IOException {
    String old_file = Config.FILE_BASE + File.separatorChar + Config.FILE_STICKER_BASE + File.separatorChar
            + getTargetFilename();/*from w  w  w .j  a va 2  s .c om*/

    logger.trace("Old filename exists: {}", new File(old_file).exists());

    if (new File(old_file).exists()) {
        Files.copy(Paths.get(old_file), Paths.get(getTargetPathAndFilename()),
                StandardCopyOption.REPLACE_EXISTING);
        return;
    }
    super.download();
}

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

protected void untarbz2(File zip, File toDir) throws IOException {
    File tar = new File(zip.getAbsolutePath().replace(".tar.bz2", ".tar"));

    try (FileInputStream fin = new FileInputStream(zip);
            BufferedInputStream bin = new BufferedInputStream(fin);
            BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(bin)) {
        Files.copy(bzIn, tar.toPath(), REPLACE_EXISTING);
    }//from  ww  w.j  a  v a 2  s . co m

    untar(tar, toDir);
}

From source file:com.google.devtools.build.lib.bazel.repository.CompressedTarFunction.java

@Override
public Path decompress(DecompressorDescriptor descriptor) throws RepositoryFunctionException {
    Optional<String> prefix = descriptor.prefix();
    boolean foundPrefix = false;

    try (InputStream decompressorStream = getDecompressorStream(descriptor)) {
        TarArchiveInputStream tarStream = new TarArchiveInputStream(decompressorStream);
        TarArchiveEntry entry;//  ww  w .ja v  a2s  .  c  o m
        while ((entry = tarStream.getNextTarEntry()) != null) {
            StripPrefixedPath entryPath = StripPrefixedPath.maybeDeprefix(entry.getName(), prefix);
            foundPrefix = foundPrefix || entryPath.foundPrefix();
            if (entryPath.skip()) {
                continue;
            }

            Path filename = descriptor.repositoryPath().getRelative(entryPath.getPathFragment());
            FileSystemUtils.createDirectoryAndParents(filename.getParentDirectory());
            if (entry.isDirectory()) {
                FileSystemUtils.createDirectoryAndParents(filename);
            } else {
                if (entry.isSymbolicLink() || entry.isLink()) {
                    PathFragment linkName = new PathFragment(entry.getLinkName());
                    boolean wasAbsolute = linkName.isAbsolute();
                    // Strip the prefix from the link path if set.
                    linkName = StripPrefixedPath.maybeDeprefix(linkName.getPathString(), prefix)
                            .getPathFragment();
                    if (wasAbsolute) {
                        // Recover the path to an absolute path as maybeDeprefix() relativize the path
                        // even if the prefix is not set
                        linkName = descriptor.repositoryPath().getRelative(linkName).asFragment();
                    }
                    if (entry.isSymbolicLink()) {
                        FileSystemUtils.ensureSymbolicLink(filename, linkName);
                    } else {
                        FileSystemUtils.createHardLink(filename,
                                descriptor.repositoryPath().getRelative(linkName));
                    }
                } else {
                    Files.copy(tarStream, filename.getPathFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
                    filename.chmod(entry.getMode());

                    // This can only be done on real files, not links, or it will skip the reader to
                    // the next "real" file to try to find the mod time info.
                    Date lastModified = entry.getLastModifiedDate();
                    filename.setLastModifiedTime(lastModified.getTime());
                }
            }
        }
    } catch (IOException e) {
        throw new RepositoryFunctionException(e, Transience.TRANSIENT);
    }

    if (prefix.isPresent() && !foundPrefix) {
        throw new RepositoryFunctionException(
                new IOException("Prefix " + prefix.get() + " was given, but not found in the archive"),
                Transience.PERSISTENT);
    }

    return descriptor.repositoryPath();
}