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:im.bci.gamesitekit.GameSiteKitMain.java

private void copyScreenshots() throws IOException {
    Files.createDirectories(screenshotsOutputDir);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(screenshotsInputDir, IMAGE_GLOB)) {
        for (Path image : stream) {
            Files.copy(image, screenshotsOutputDir.resolve(screenshotsInputDir.relativize(image)));
        }/*from  w ww  . jav  a 2s .  co m*/
    }
    Files.createDirectories(screenshotThumbnailsOutputDir);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(screenshotThumbnailsInputDir, IMAGE_GLOB)) {
        for (Path image : stream) {
            Files.copy(image,
                    screenshotThumbnailsOutputDir.resolve(screenshotThumbnailsInputDir.relativize(image)));
        }
    }
}

From source file:fr.ortolang.diffusion.usecase.StoreAndRetrieveFileUseCase.java

@Test
public void testHostSimpleFile() throws URISyntaxException {
    // Path origin = Paths.get(HostAndRetrieveFileTest.class.getClassLoader().getResource("file1.jpg").getPath());
    Path origin = Paths.get("/home/jerome/Images/test.jpg");
    LOGGER.log(Level.INFO, "Origin file to insert in container : " + origin.toString());

    Path destination = Paths.get("/tmp/" + System.currentTimeMillis());
    LOGGER.log(Level.INFO,/*from  w  w w  . j av  a  2 s.  c  o  m*/
            "Destination file for retrieving content from container : " + destination.toString());

    String wkey = UUID.randomUUID().toString();
    String okey = UUID.randomUUID().toString();

    // Create a Workspace
    try {
        core.createWorkspace(wkey, "Test Workspace", "test");
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Create the Digital Object
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Files.copy(origin, baos);
        //core.createDataObject(wkey, "/" + okey, "Test Object", "A really simple test object !!", baos.toByteArray());
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Check that the object is registered in the browser
    try {
        OrtolangObjectIdentifier identifier = browser.lookup(okey);
        assertEquals(identifier.getService(), CoreService.SERVICE_NAME);
        assertEquals(identifier.getType(), DataObject.OBJECT_TYPE);
    } catch (BrowserServiceException | KeyNotFoundException | AccessDeniedException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Retrieve this digital object informations using the key
    try {
        DataObject object = core.readDataObject(okey);
        LOGGER.log(Level.INFO, "Detected mime type : " + object.getMimeType());
        LOGGER.log(Level.INFO, "Detected size : " + object.getSize());
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Retrieve this digital object data using the key
    try {
        //byte[] data = core.readDataObjectContent(okey);
        //Files.copy(new ByteArrayInputStream(data), destination);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Compare origin and destination :
    try {
        InputStream input1 = Files.newInputStream(origin);
        InputStream input2 = Files.newInputStream(destination);
        assertTrue(IOUtils.contentEquals(input1, input2));
        input1.close();
        input2.close();
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        fail(e.getMessage());
    }

    // Delete destination
    try {
        Files.delete(destination);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:io.sloeber.core.managers.Manager.java

/**
 * Given a platform description in a json file download and install all
 * needed stuff. All stuff is including all tools and core files and
 * hardware specific libraries. That is (on windows) inclusive the make.exe
 *
 * @param platform//from   w  w  w.ja v  a  2s .  c o  m
 * @param monitor
 * @param object
 * @return
 */
static public IStatus downloadAndInstall(ArduinoPlatform platform, boolean forceDownload,
        IProgressMonitor monitor) {

    IStatus status = downloadAndInstall(platform.getUrl(), platform.getArchiveFileName(),
            platform.getInstallPath(), forceDownload, monitor);
    if (!status.isOK()) {
        return status;
    }
    MultiStatus mstatus = new MultiStatus(status.getPlugin(), status.getCode(), status.getMessage(),
            status.getException());

    if (platform.getToolsDependencies() != null) {
        for (ToolDependency tool : platform.getToolsDependencies()) {
            monitor.setTaskName(InstallProgress.getRandomMessage());
            mstatus.add(tool.install(monitor));
        }
    }
    // On Windows install make from equations.org
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        try {
            Path makePath = Paths
                    .get(ConfigurationPreferences.getPathExtensionPath().append("make.exe").toString()); //$NON-NLS-1$
            if (!makePath.toFile().exists()) {
                Files.createDirectories(makePath.getParent());
                URL makeUrl = new URL("ftp://ftp.equation.com/make/32/make.exe"); //$NON-NLS-1$
                Files.copy(makeUrl.openStream(), makePath);
                makePath.toFile().setExecutable(true, false);

            }
        } catch (IOException e) {
            mstatus.add(new Status(IStatus.ERROR, Activator.getId(), Messages.Manager_Downloading_make_exe, e));
        }
    }

    return mstatus.getChildren().length == 0 ? Status.OK_STATUS : mstatus;

}

From source file:com.cloudbees.jenkins.support.util.OutputStreamSelectorTest.java

@Test
public void shouldUseBinaryStreamForPNG() throws IOException {
    Path pngFile = Paths.get("src/main/webapp/images/16x16/support.png");
    ByteArrayOutputStream expectedStreamContents = new ByteArrayOutputStream();
    Files.copy(pngFile, expectedStreamContents);
    Files.copy(pngFile, selector);
    byte[] expected = expectedStreamContents.toByteArray();
    assertThat(textOut.toByteArray()).isEmpty();
    assertThat(binaryOut.toByteArray()).isNotEmpty().isEqualTo(expected);
}

From source file:com.netflix.nicobar.core.persistence.PathArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleDir = rootDir.resolve(moduleId.toString());
    if (Files.exists(moduleDir)) {
        FileUtils.deleteDirectory(moduleDir.toFile());
    }//from ww  w .j  a  v a  2  s  .com
    JarFile jarFile;
    try {
        jarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    try {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            Path entryName = moduleDir.resolve(jarEntry.getName());
            if (jarEntry.isDirectory()) {
                Files.createDirectories(entryName);
            } else {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                try {
                    Files.copy(inputStream, entryName);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(jarFile);
    }
    // write the module spec
    String serialized = moduleSpecSerializer.serialize(moduleSpec);
    Files.write(moduleDir.resolve(moduleSpecSerializer.getModuleSpecFileName()),
            serialized.getBytes(Charsets.UTF_8));

    // update the timestamp on the module directory to indicate that the module has been updated
    Files.setLastModifiedTime(moduleDir, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:com.gitpitch.services.DiskService.java

public void copyDirectory(Path source, Path dest) {

    log.debug("copyDirectory: source={}, dest={}", source, dest);

    try {// w ww.j  a  v a  2 s  . c  o  m

        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {

            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

                Path relative = source.relativize(dir);
                Path visitPath = Paths.get(dest.toString(), relative.toString());
                ensure(visitPath);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                Path copyTarget = Paths.get(dest.toString(), source.relativize(file).toString());
                if (!file.getFileName().toString().matches("\\..*")
                        && !copyTarget.getFileName().toString().matches("\\..*")) {
                    Files.copy(file, copyTarget);
                }
                return FileVisitResult.CONTINUE;
            }
        });

    } catch (Exception cex) {
        log.warn("copyDirectory: source={}, dest={}, ex={}", source, dest, cex);
    }
}

From source file:gov.vha.isaac.rf2.filter.RF2Filter.java

@Override
public void execute() throws MojoExecutionException {
    if (!inputDirectory.exists() || !inputDirectory.isDirectory()) {
        throw new MojoExecutionException("Path doesn't exist or isn't a folder: " + inputDirectory);
    }//from   w  w w . ja va 2  s . c  om

    if (module == null) {
        throw new MojoExecutionException("You must provide a module or namespace for filtering");
    }

    moduleStrings_.add(module + "");

    outputDirectory.mkdirs();
    File temp = new File(outputDirectory, inputDirectory.getName());
    temp.mkdirs();

    Path source = inputDirectory.toPath();
    Path target = temp.toPath();
    try {
        getLog().info("Reading from " + inputDirectory.getAbsolutePath());
        getLog().info("Writing to " + outputDirectory.getCanonicalPath());

        summary_.append("This content was filtered by an RF2 filter tool.  The parameters were module: "
                + module + " software version: " + converterVersion);
        summary_.append("\r\n\r\n");

        getLog().info("Checking for nested child modules");

        //look in sct2_Relationship_ files, find anything where the 6th column (destinationId) is the 
        //starting module ID concept - and add that sourceId (5th column) to our list of modules to extract
        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toFile().getName().startsWith("sct2_Relationship_")) {
                    //don't look for quotes, the data is bad, and has floating instances of '"' all by itself
                    CSVReader csvReader = new CSVReader(
                            new InputStreamReader(new FileInputStream(file.toFile())), '\t',
                            CSVParser.NULL_CHARACTER);
                    String[] line = csvReader.readNext();
                    if (!line[4].equals("sourceId") || !line[5].equals("destinationId")) {
                        csvReader.close();
                        throw new IOException("Unexpected error looking for nested modules");
                    }
                    line = csvReader.readNext();
                    while (line != null) {
                        if (line[5].equals(moduleStrings_.get(0))) {
                            moduleStrings_.add(line[4]);
                        }
                        line = csvReader.readNext();
                    }
                    csvReader.close();
                }
                return FileVisitResult.CONTINUE;
            }
        });

        log("Full module list (including detected nested modules: "
                + Arrays.toString(moduleStrings_.toArray(new String[moduleStrings_.size()])));

        Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetdir = target.resolve(source.relativize(dir));
                try {
                    //this just creates the sub-directory in the target
                    Files.copy(dir, targetdir);
                } catch (FileAlreadyExistsException e) {
                    if (!Files.isDirectory(targetdir))
                        throw e;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                handleFile(file, target.resolve(source.relativize(file)));
                return FileVisitResult.CONTINUE;
            }
        });

        Files.write(new File(temp, "FilterInfo.txt").toPath(), summary_.toString().getBytes(),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
        throw new MojoExecutionException("Failure", e);
    }

    getLog().info("Filter Complete");

}

From source file:com.github.jrialland.ajpclient.AbstractTomcatTest.java

@SuppressWarnings("serial")
protected void addStaticResource(final String mapping, final Path file) {

    if (!Files.isRegularFile(file)) {
        final FileNotFoundException fnf = new FileNotFoundException(file.toString());
        fnf.fillInStackTrace();// w  w w. ja  v a2 s. c om
        throw new IllegalArgumentException(fnf);
    }

    String md5;
    try {
        final InputStream is = file.toUri().toURL().openStream();
        md5 = computeMd5(is);
        is.close();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
    final String fMd5 = md5;

    addServlet(mapping, new HttpServlet() {
        @Override
        protected void service(final HttpServletRequest req, final HttpServletResponse resp)
                throws ServletException, IOException {
            resp.setContentLength((int) Files.size(file));
            resp.setHeader("Content-MD5", fMd5);
            final String mime = Files.probeContentType(file);
            if (mime != null) {
                resp.setContentType(mime);
            }
            final OutputStream out = resp.getOutputStream();
            Files.copy(file, out);
            out.flush();
        }
    });
}

From source file:hu.tbognar76.apking.ApKing.java

private void reportPhoneNewerInDB() {
    ArrayList<String> log = new ArrayList<String>();
    for (DeviceApp app : this.dmanager.apps) {
        // HashMap<String, ArrayList<ApkInfo>> packageHash = null;
        if (this.packageHash.get(app.packageName) != null) {
            // System.out.println(app.packageName);
            ArrayList<ApkInfo> aai = this.packageHash.get(app.packageName);
            for (ApkInfo ai : aai) {
                if (new ComparableVersion(ai.version).compareTo(new ComparableVersion(app.versionName)) > 0) {
                    String line = concatWithPos(concatWithPos(ai.name, ai.version, 35),
                            "on phone: " + app.versionName, 50);
                    log.add(line);//from   ww w .j a va 2 s  .co m
                    // ai.fullpath
                    if (this.init.isCopyNewerFilesToUpdatePath) {
                        Path sourcePath = Paths.get(ai.fullpath);
                        Path destinationPath = Paths.get(this.init.updatePath + ai.filename);
                        try {
                            Files.copy(sourcePath, destinationPath);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                }
            }
        }
    }

    Collections.sort(log, (p1, p2) -> p1.compareTo(p2));
    for (String line : log) {
        System.out.println(line);
    }

}

From source file:com.excelsiorjet.maven.plugin.JetMojo.java

private void copyDependency(File from, File to, File buildDir, ArrayList<String> dependencies) {
    try {//from ww w. j  av a2s .c  o m
        if (!to.exists()) {
            Files.copy(from.toPath(), to.toPath());
        }
        dependencies.add(buildDir.toPath().relativize(to.toPath()).toString());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}