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.btkelly.gnag.tasks.CheckLocalTask.java

private void copyCssFile(final File gnagReportDirectory) throws IOException {
    final InputStream gnagCssFileInputStream = getClass().getClassLoader().getResourceAsStream(CSS_FILE_NAME);

    Enumeration<URL> e = getClass().getClassLoader().getResources(".");
    while (e.hasMoreElements()) {
        System.out.println(e.nextElement());
    }//from ww w  .ja  va2 s . com

    final Path gnagCssFileTargetPath = Paths.get(gnagReportDirectory.getAbsolutePath(), CSS_FILE_NAME);

    try {
        Files.copy(gnagCssFileInputStream, gnagCssFileTargetPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (final IOException ignored) {
        Logger.logError("Error copying CSS file for local report.");
    } finally {
        try {
            gnagCssFileInputStream.close();
        } catch (final IOException ignored) {
        }
    }

}

From source file:com.aspose.barcode.maven.examples.AsposeExampleSupport.java

public void createExample() {
    String srcExamplePath = System.getProperty("user.home") + File.separator + localExampleFolder
            + File.separator + localExampleSourceFolder;
    String srcExampleResourcePath = System.getProperty("user.home") + File.separator + localExampleFolder
            + File.separator + localExampleResourceFolder;

    String destProjectExamplePath = selectedProjectPath + File.separator + localExampleSourceFolder;
    String destProjectExampleResourcePath = selectedProjectPath + File.separator + localExampleResourceFolder;

    File srcExampleCategoryPath = new File(srcExamplePath + File.separator + exampleCategory);
    File destExampleCategoryPath = new File(destProjectExamplePath + File.separator + exampleCategory);

    Path srcUtil = new File(srcExamplePath + File.separator + "Utils.java").toPath();
    Path destUtil = new File(destProjectExamplePath + File.separator + "Utils.java").toPath();

    File srcExampleResourceCategoryPath = new File(srcExampleResourcePath + File.separator + exampleCategory);
    File destExampleResourceCategoryPath = new File(
            destProjectExampleResourcePath + File.separator + exampleCategory);

    String repositoryPOM_XML = System.getProperty("user.home") + File.separator + localExampleFolder
            + File.separator + AsposeConstants.MAVEN_POM_XML;

    try {//w w w  .  j ava 2s  .co m
        FileUtils.copyDirectory(srcExampleCategoryPath, destExampleCategoryPath);
        Files.copy(srcUtil, destUtil, StandardCopyOption.REPLACE_EXISTING);
        FileUtils.copyDirectory(srcExampleResourceCategoryPath, destExampleResourceCategoryPath);

        NodeList examplesNoneAsposeDependencies = AsposeMavenProjectManager.getInstance()
                .getDependenciesFromPOM(repositoryPOM_XML, AsposeConstants.ASPOSE_GROUP_ID);
        AsposeMavenProjectManager.getInstance().addMavenDependenciesInProject(examplesNoneAsposeDependencies);

        NodeList examplesNoneAsposeRepositories = AsposeMavenProjectManager.getInstance()
                .getRepositoriesFromPOM(repositoryPOM_XML, AsposeConstants.ASPOSE_MAVEN_REPOSITORY);
        AsposeMavenProjectManager.getInstance().addMavenRepositoriesInProject(examplesNoneAsposeRepositories);

        project.refreshLocal(IResource.DEPTH_INFINITE, null);

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

}

From source file:com.netflix.nicobar.cassandra.CassandraArchiveRepositoryTest.java

@BeforeClass
public void setup() throws Exception {
    gateway = mock(CassandraGateway.class);
    Keyspace mockKeyspace = mock(Keyspace.class);
    when(mockKeyspace.getKeyspaceName()).thenReturn("testKeySpace");

    when(gateway.getKeyspace()).thenReturn(mockKeyspace);
    when(gateway.getColumnFamily()).thenReturn("testColumnFamily");

    config = new BasicCassandraRepositoryConfig.Builder(gateway).setRepositoryId("TestRepo")
            .setArchiveOutputDirectory(Files.createTempDirectory(this.getClass().getSimpleName() + "_"))
            .build();/*from  www  .  java2 s.c  om*/
    repository = new CassandraArchiveRepository(config);

    URL testJarUrl = getClass().getClassLoader()
            .getResource(TestResource.TEST_HELLOWORLD_JAR.getResourcePath());
    if (testJarUrl == null) {
        fail("Couldn't locate " + TestResource.TEST_HELLOWORLD_JAR.getResourcePath());
    }
    testArchiveJarFile = Files.createTempFile(TestResource.TEST_HELLOWORLD_JAR.getModuleId().toString(),
            ".jar");
    InputStream inputStream = testJarUrl.openStream();
    Files.copy(inputStream, testArchiveJarFile, StandardCopyOption.REPLACE_EXISTING);
    IOUtils.closeQuietly(inputStream);
}

From source file:org.apache.jmeter.report.dashboard.TemplateVisitor.java

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

    // Depending on file extension, copy or process file
    String extension = FilenameUtils.getExtension(file.toString());
    if (TEMPLATED_FILE_EXT.equalsIgnoreCase(extension)) {
        // Process template file
        String templatePath = source.relativize(file).toString();
        Template template = configuration.getTemplate(templatePath);
        Path newPath = target.resolve(FilenameUtils.removeExtension(templatePath));
        try (FileOutputStream stream = new FileOutputStream(newPath.toString());
                Writer writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8);
                BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
            template.process(data, bufferedWriter);
        } catch (TemplateException ex) {
            throw new IOException(ex);
        }/*from  w  ww.  j a  va 2  s. c  om*/

    } else {
        // Copy regular file
        Path newFile = target.resolve(source.relativize(file));
        Files.copy(file, newFile, StandardCopyOption.REPLACE_EXISTING);
    }
    return FileVisitResult.CONTINUE;
}

From source file:com.cyc.corpus.nlmpaper.AIMedOpenAccessPaper.java

private Optional<AIMedArticle> get() {
    if (paper != null) {
        return Optional.of(paper);
    }/* ww  w.j  a v a  2  s .c  o m*/

    try {
        Optional<Path> xmlpath = getPaperPath();
        if (xmlpath.isPresent()) {
            Path destinationD = Paths.get(basedir, "AIMedOpenAccess", "XML");

            if (Files.notExists(destinationD, LinkOption.NOFOLLOW_LINKS)) {
                Files.createDirectory(destinationD);
            }

            Path extractTo = Paths.get(basedir, "AIMedOpenAccess", "XML",
                    xmlpath.get().getFileName().toString());

            Files.copy(xmlpath.get(), extractTo, StandardCopyOption.REPLACE_EXISTING);

            // specify the location and name of xml file to be read  
            File xmlFile = extractTo.toFile();
            String articleString = FileUtils.readFileToString(xmlFile).trim();
            paper = new AIMedArticle(articleString);

            return Optional.of(paper);
        }
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
        return Optional.empty();
    }

    return Optional.empty();
}

From source file:com.github.zhanhb.ckfinder.connector.utils.ImageUtils.java

/**
 * Uploads image and if the image size is larger than maximum allowed it
 * resizes the image./*from w  ww .j a  va2s.c  o  m*/
 *
 * @param part servlet part
 * @param file file name
 * @param fileName name of file
 * @param context ckfinder context
 * @throws IOException when IO Exception occurs.
 */
public static void createTmpThumb(InputStreamSource part, Path file, String fileName, CKFinderContext context)
        throws IOException {
    BufferedImage image;
    try (InputStream stream = part.getInputStream()) {
        image = ImageIO.read(stream);
        if (image == null) {
            throw new IOException("Wrong file");
        }
    }
    ImageProperties imageProperties = context.getImage();
    Dimension dimension = createThumbDimension(image, imageProperties.getMaxWidth(),
            imageProperties.getMaxHeight());
    if (dimension.width == 0 || dimension.height == 0
            || (image.getHeight() <= dimension.height && image.getWidth() <= dimension.width)) {
        try (InputStream stream = part.getInputStream()) {
            Files.copy(stream, file, StandardCopyOption.REPLACE_EXISTING);
        }
    } else {
        resizeImage(image, dimension.width, dimension.height, imageProperties.getQuality(), file);
    }
    if (log.isTraceEnabled()) {
        log.trace("thumb size: {}", Files.size(file));
    }
}

From source file:com.kantenkugel.discordbot.moduleutils.DocParser.java

private static void download() {
    LOG.info("Downloading source-file");
    try {/*from  w  w w  .  j  ava 2 s.  com*/
        HttpResponse<String> response = Unirest.get(JENKINS_PREFIX + ARTIFACT_SUFFIX).asString();
        if (response.getStatus() < 300 && response.getStatus() > 199) {
            JSONArray artifacts = new JSONObject(response.getBody()).getJSONArray("artifacts");
            for (int i = 0; i < artifacts.length(); i++) {
                JSONObject artifact = artifacts.getJSONObject(i);
                if (artifact.getString("fileName").endsWith("sources.jar")) {
                    URL artifactUrl = new URL(
                            JENKINS_PREFIX + "artifact/" + artifact.getString("relativePath"));
                    InputStream is = artifactUrl.openStream();
                    Files.copy(is, LOCAL_SRC_PATH, StandardCopyOption.REPLACE_EXISTING);
                    is.close();
                    LOG.info("Done downloading source-file");
                }
            }
        }
    } catch (UnirestException | IOException e) {
        LOG.log(e);
    }
}

From source file:com.ibm.liberty.starter.api.v1.LibertyFileUploader.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String tech = request.getParameter(PARAMETER_TECH);
    String workspaceId = request.getParameter(PARAMETER_WORKSPACE); //specify the unique workspace directory to upload the file(s) to.   
    Collection<Part> filePartCollection = request.getParts();

    String serverHostPort = request.getRequestURL().toString().replace(request.getRequestURI(), "");
    int schemeLength = request.getScheme().toString().length();
    String internalHostPort = "http" + serverHostPort.substring(schemeLength);
    log.log(Level.FINER, "serverHostPort : " + serverHostPort);
    final ServiceConnector serviceConnector = new ServiceConnector(serverHostPort, internalHostPort);
    HashMap<Part, String> fileNames = new HashMap<Part, String>();
    if (!isValidRequest(request, response, tech, workspaceId, filePartCollection, serviceConnector,
            fileNames)) {//ww  w.ja v  a2 s .c om
        return;
    }

    Service techService = serviceConnector.getServiceObjectFromId(tech);
    String techDirPath = StarterUtil.getWorkspaceDir(workspaceId) + "/" + techService.getId();
    File techDir = new File(techDirPath);
    if (techDir.exists() && techDir.isDirectory()
            && "true".equalsIgnoreCase(request.getParameter(PARAMETER_CLEANUP))) {
        FileUtils.cleanDirectory(techDir);
        log.log(Level.FINER, "Cleaned up tech workspace directory : " + techDirPath);
    }

    for (Part filePart : filePartCollection) {
        if (!techDir.exists()) {
            FileUtils.forceMkdir(techDir);
            log.log(Level.FINER, "Created tech directory :" + techDirPath);
        }

        String filePath = techDirPath + "/" + fileNames.get(filePart);
        log.log(Level.FINER, "File path : " + filePath);
        File uploadedFile = new File(filePath);

        Files.copy(filePart.getInputStream(), uploadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        log.log(Level.FINE, "Copied file to " + filePath);
    }

    if ("true".equalsIgnoreCase(request.getParameter(PARAMETER_PROCESS))) {
        // Process uploaded file(s)
        String processResult = serviceConnector.processUploadedFiles(techService, techDirPath);
        if (!processResult.equalsIgnoreCase("success")) {
            log.log(Level.INFO,
                    "Error processing the files uploaded to " + techDirPath + " : Result=" + processResult);
            response.sendError(500, processResult);
            return;
        }
        log.log(Level.FINE, "Processed the files uploaded to " + techDirPath);
    }

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("success");
    out.close();
}

From source file:com.seleniumtests.driver.DriverExtractor.java

public void copyDriver(String driverName) {
    InputStream driver = Thread.currentThread().getContextClassLoader().getResourceAsStream(String
            .format("drivers/%s/%s%s", os, driverName, OSUtilityFactory.getInstance().getProgramExtension()));

    if (driver == null) {
        throw new DriverExceptions(String.format("Driver %s does not exist in resources", driverName));
    }// w  w w. j a  va 2s  .  c  o m
    Path driverPath = getDriverPath(driverName);

    driverPath.toFile().getParentFile().mkdirs();

    try {
        Files.copy(driver, driverPath, StandardCopyOption.REPLACE_EXISTING);
        driverPath.toFile().setExecutable(true);
        logger.info(String.format("Driver %s copied to %s", driverName, driverPath));
    } catch (IOException e) {
        logger.info(String.format("Driver not copied: %s - it may be in use", driverName));
    }

}