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:ccm.pay2spawn.configurator.HTMLGenerator.java

public static void init() throws IOException {
    htmlFolder = new File(Pay2Spawn.getFolder(), "html");
    templateFolder = new File(htmlFolder, "templates");
    //noinspection ResultOfMethodCallIgnored
    templateFolder.mkdirs();/*from w  ww  . ja v  a 2 s .  com*/

    templateIndex = new File(templateFolder, "index.html");
    if (!templateIndex.exists()) {
        InputStream link = (HTMLGenerator.class.getResourceAsStream("/p2sTemplates/index.html"));
        Files.copy(link, templateIndex.getAbsoluteFile().toPath());
    }
    TypeRegistry.copyTemplates();
}

From source file:dyco4j.instrumentation.entry.CLI.java

private static void processCommandLine(final CommandLine cmdLine) throws IOException {
    final Path _srcRoot = Paths.get(cmdLine.getOptionValue(IN_FOLDER_OPTION));
    final Path _trgRoot = Paths.get(cmdLine.getOptionValue(OUT_FOLDER_OPTION));

    final Predicate<Path> _nonClassFileSelector = p -> !p.toString().endsWith(".class")
            && Files.isRegularFile(p);
    final BiConsumer<Path, Path> _fileCopier = (srcPath, trgPath) -> {
        try {//from w w w  .j  av  a 2 s  .  c o  m
            Files.copy(srcPath, trgPath);
        } catch (final IOException _ex) {
            throw new RuntimeException(_ex);
        }
    };
    processFiles(_srcRoot, _trgRoot, _nonClassFileSelector, _fileCopier);

    final Predicate<Path> _classFileSelector = p -> p.toString().endsWith(".class");
    final String _methodNameRegex = cmdLine.getOptionValue(METHOD_NAME_REGEX_OPTION, METHOD_NAME_REGEX);
    final Boolean _onlyAnnotatedTests = cmdLine.hasOption(ONLY_ANNOTATED_TESTS_OPTION);
    final BiConsumer<Path, Path> _classInstrumenter = (srcPath, trgPath) -> {
        try {
            final byte[] _bytecode = Files.readAllBytes(srcPath);
            final ClassReader _cr = new ClassReader(_bytecode);
            final ClassWriter _cw = new ClassWriter(_cr, ClassWriter.COMPUTE_MAXS);
            final ClassVisitor _cv1 = new LoggerInitializingClassVisitor(CLI.ASM_VERSION, _cw);
            final ClassVisitor _cv2 = new TracingClassVisitor(_cv1, _methodNameRegex, _onlyAnnotatedTests);
            _cr.accept(_cv2, 0);
            final byte[] _out = _cw.toByteArray();
            Files.write(trgPath, _out);
        } catch (final IOException _ex) {
            throw new RuntimeException(_ex);
        }
    };
    processFiles(_srcRoot, _trgRoot, _classFileSelector, _classInstrumenter);
}

From source file:com.baifendian.swordfish.webserver.service.storage.FileSystemStorageService.java

/**
 * ?, /* ww  w  . j a v  a2  s  .  com*/
 *
 * @param file
 * @param destFilename
 */
@Override
public void store(MultipartFile file, String destFilename) {
    try {
        if (file.isEmpty()) {
            throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
        }

        File destFile = new File(destFilename);
        File destDir = new File(destFile.getParent());

        if (!destDir.exists()) {
            FileUtils.forceMkdir(destDir);
        }

        Files.copy(file.getInputStream(), Paths.get(destFilename));
    } catch (IOException e) {
        throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
    }
}

From source file:com.github.ffremont.microservices.springboot.node.tasks.InstallJarTask.java

@Override
public void run(MicroServiceTask task) throws TaskException {
    Path msVersionFolder = helper.targetDirOf(task.getMs());
    Path checksumPath = Paths.get(msVersionFolder.toString(), InstallTask.CHECKSUM_FILE_NAME + ".txt");
    Path jarTarget = helper.targetJarOf(task.getMs());

    try {/*from  w w w  .jav a 2s . c om*/
        if (task.getJar() == null) {
            throw new InvalidInstallationException("Jar indisponible dans l'objet MicroServiceTask");
        }

        Files.copy(task.getJar(), jarTarget);
        MessageDigest md = MessageDigest.getInstance("SHA-1");

        try (DigestInputStream digestIs = new DigestInputStream(new FileInputStream(jarTarget.toFile()), md)) {
            byte[] buffer = new byte[10240]; // 10ko
            while (0 < digestIs.read(buffer)) {
            }

            digestIs.close();
        }
        byte[] checksumTarget = md.digest();

        if (!String.format("%032X", new BigInteger(1, checksumTarget))
                .equals(task.getMs().getSha1().toUpperCase())) {
            throw new InvalidInstallationException(
                    "Le checksum n'est pas valide suite  la copie : " + this.nodeBase);
        }

        Files.write(checksumPath, task.getMs().getSha1().getBytes());
        LOG.debug("Cration du fichier checksum.txt");
    } catch (IOException | NoSuchAlgorithmException ex) {
        throw new InvalidInstallationException("Impossible d'installer le jar", ex);
    }
}

From source file:muffinc.yafdivj.helper.FeretHandler.java

public static void moveToHumans() {
    File file = new File(NEW_FOLDER);

    for (File file1 : file.listFiles()) {
        if (file1.isDirectory()) {
            for (File file2 : file1.listFiles(((FileFilter) new RegexFileFilter("\\w{10}d.*")))) {

                try {
                    String newFolder = "/Users/Meth/Documents/FROG/src/test/resources/Humans/" + "H_"
                            + file2.getName().substring(1, 5) + "/";

                    File file3 = new File(newFolder);

                    if (!file3.exists()) {
                        file3.mkdirs();//from   ww w  .  j ava  2s.  c om
                    }

                    Files.copy(file2.toPath(), new File(newFolder + file2.getName()).toPath());

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.liferay.sync.engine.documentlibrary.handler.DownloadFileHandler.java

@Override
protected void doHandleResponse(HttpResponse httpResponse) throws Exception {

    InputStream inputStream = null;

    try {//from   w  w w . ja  v a 2 s .c o  m
        SyncFile syncFile = (SyncFile) getParameterValue("syncFile");

        Path filePath = Paths.get(syncFile.getFilePathName());

        HttpEntity httpEntity = httpResponse.getEntity();

        inputStream = httpEntity.getContent();

        Path tempFilePath = Files.createTempFile(String.valueOf(filePath.getFileName()), ".tmp");

        if (Files.exists(filePath)) {
            Files.copy(filePath, tempFilePath);
        }

        if ((Boolean) getParameterValue("patch")) {
            IODeltaUtil.patch(tempFilePath, inputStream);
        } else {
            Files.copy(inputStream, tempFilePath, StandardCopyOption.REPLACE_EXISTING);
        }

        syncFile.setFileKey(FileUtil.getFileKey(tempFilePath));
        syncFile.setState(SyncFile.STATE_SYNCED);
        syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED);

        SyncFileService.update(syncFile);

        Files.move(tempFilePath, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } finally {
        StreamUtil.cleanUp(inputStream);
    }
}

From source file:com.arcanix.php.phar.PharEntry.java

public PharEntry(final File file, final String localPath, final PharCompression pharCompression)
        throws IOException {
    this.file = file;
    this.localPath = localPath;
    this.pharCompression = pharCompression;

    byte[] uncompressedBytes = Files.readAllBytes(this.file.toPath());
    this.checksum = new CRC32();
    this.checksum.update(uncompressedBytes);

    ByteArrayOutputStream compressed = new ByteArrayOutputStream();

    OutputStream compressor = null;
    try {/*from  w w w.  java2  s.  com*/
        compressor = getCompressorOutputStream(compressed);
        Files.copy(this.file.toPath(), compressor);
        compressor.flush();
    } finally {
        compressor.close();
    }

    this.compressedBytes = compressed.toByteArray();
}

From source file:de.alexkamp.sandbox.model.SandboxData.java

public SandboxData copyTo(InputStream source, String target) throws IOException {
    File targetFile = new File(basePath, target);
    ensureExistance(targetFile);/* w  w  w  .j  a v  a 2 s. co  m*/
    Files.copy(source, targetFile.toPath());
    return this;
}

From source file:com.google.cloud.tools.gradle.appengine.sourcecontext.SourceContextPluginIntegrationTest.java

/** Create a test project with git source context. */
public void setUpTestProject() throws IOException {
    Path buildFile = testProjectDir.getRoot().toPath().resolve("build.gradle");

    Path src = Files.createDirectory(testProjectDir.getRoot().toPath().resolve("src"));
    InputStream buildFileContent = getClass().getClassLoader()
            .getResourceAsStream("projects/sourcecontext-project/build.gradle");
    Files.copy(buildFileContent, buildFile);

    Path gitContext = testProjectDir.getRoot().toPath().resolve("gitContext.zip");
    InputStream gitContextContent = getClass().getClassLoader()
            .getResourceAsStream("projects/sourcecontext-project/gitContext.zip");
    Files.copy(gitContextContent, gitContext);

    try (ZipFile zipFile = new ZipFile(gitContext.toFile())) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(testProjectDir.getRoot(), entry.getName());
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                entryDestination.getParentFile().mkdirs();
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);//from  w  ww  . j a v  a2 s.  c  om
                IOUtils.closeQuietly(in);
                out.close();
            }
        }
    }

    FileUtils.delete(gitContext.toFile());

    Path webInf = testProjectDir.getRoot().toPath().resolve("src/main/webapp/WEB-INF");
    Files.createDirectories(webInf);
    File appengineWebXml = Files.createFile(webInf.resolve("appengine-web.xml")).toFile();
    Files.write(appengineWebXml.toPath(), "<appengine-web-app/>".getBytes(Charsets.UTF_8));
}

From source file:com.collaide.fileuploader.helper.TestHelper.java

protected File createNewFile(String name) {
    try {/*from  ww  w . ja va  2s .  co m*/
        return Files.copy(getTestFile().toPath(), getDestFile(name).toPath()).toFile();
    } catch (IOException ex) {
        logger.error("Error while copying", ex);
    }
    return null;
}