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:com.stratio.mojo.scala.crossbuild.RewriteJUnitXMLTest.java

@Test
public void rewrite() throws IOException {
    for (final String[] reportPair : reports) {
        final String origReport = reportPair[0];
        final String resultReport = reportPair[1];
        final RewriteJUnitXML rewriter = new RewriteJUnitXML();
        tempDir.create();//from w  ww  .  j  a  v a 2 s.c o m
        final File file = tempDir.newFile();
        file.delete();
        Files.copy(getClass().getResourceAsStream(origReport), file.toPath());
        final String newBinaryVersion = "2.11";
        rewriter.rewrite(file, newBinaryVersion);
        assertEqualToResource(file, resultReport);
        file.delete();
    }
}

From source file:de.blizzy.backup.vfs.filesystem.FileSystemFileOrFolder.java

@Override
public void copy(IOutputStreamProvider outputStreamProvider) throws IOException {
    OutputStream out = null;/*w  ww. j a v a 2  s .c om*/
    try {
        out = outputStreamProvider.getOutputStream();
        Files.copy(file.toPath(), out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:eu.esdihumboldt.hale.io.codelist.InspireCodeListAdvisor.java

@Override
public void copyResource(LocatableInputSupplier<? extends InputStream> resource, final Path target,
        IContentType resourceType, boolean includeRemote, IOReporter reporter) throws IOException {

    URI uri = resource.getLocation();
    String uriScheme = uri.getScheme();
    if (uriScheme.equals("http")) {
        // Get the response for the given uri
        Response response = INSPIRECodeListReader.getResponse(uri);

        // Handle the fluent response
        response.handleResponse(new ResponseHandler<Boolean>() {

            @Override/* w w  w  . j  a v a2 s . c  o m*/
            public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                StatusLine status = response.getStatusLine();
                HttpEntity entity = response.getEntity();

                if (status.getStatusCode() >= 300) {
                    throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
                }
                if (entity == null) {
                    throw new ClientProtocolException();
                }
                // Copy the resource file to the target path
                Files.copy(entity.getContent(), target);
                return true;
            }
        });
    } else {
        super.copyResource(resource, target, resourceType, includeRemote, reporter);
    }
}

From source file:TypeServiceTest.java

@Before
public void setUp() throws IOException {
    if (!Files.exists(fileSystemProvider.getFileSystem().getPath("/type-periodical.xml"))) {
        Files.copy(TypeServiceTest.class.getResourceAsStream("/type-periodical.xml"),
                fileSystemProvider.getFileSystem().getPath("/type-periodical.xml"));
    }/*from  w w w  . ja  va  2 s . c o  m*/
}

From source file:jhi.buntata.server.NodeMedia.java

@Put
public boolean putMedia(Representation entity) {
    if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
        try {//from   w  w w . jav a2  s. com
            BuntataNode node = nodeDAO.get(id);

            DiskFileItemFactory factory = new DiskFileItemFactory();
            RestletFileUpload upload = new RestletFileUpload(factory);
            FileItemIterator fileIterator = upload.getItemIterator(entity);

            if (fileIterator.hasNext()) {
                String nodeName = node.getName().replace(" ", "-");
                File dir = new File(dataDir, nodeName);
                dir.mkdirs();

                FileItemStream fi = fileIterator.next();

                String name = fi.getName();

                File file = new File(dir, name);

                int i = 1;
                while (file.exists())
                    file = new File(dir, (i++) + name);

                // Copy the file to its target location
                Files.copy(fi.openStream(), file.toPath());

                // Create the media entity
                String relativePath = new File(dataDir).toURI().relativize(file.toURI()).getPath();
                BuntataMedia media = new BuntataMedia(null, new Date(), new Date())
                        .setInternalLink(relativePath).setName(name).setDescription(name).setMediaTypeId(1L);
                mediaDAO.add(media);

                // Create the node media entity
                nodeMediaDAO.add(new BuntataNodeMedia().setMediaId(media.getId()).setNodeId(node.getId()));

                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
    }

    return false;
}

From source file:br.pucminas.ri.jsearch.rest.controller.ApiController.java

public static Object fileUpload(Request req, Response res) {
    req.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
    Path out = Paths.get("result/queries.txt");

    try (InputStream is = req.raw().getPart("uploaded_file").getInputStream()) {
        Path folder = Paths.get("result");
        if (Files.exists(folder)) {
            Files.delete(out);/*from   w  w w. j  a  v a 2 s.co  m*/
        }
        Files.createDirectories(Paths.get("result"));
        Files.copy(is, out);
        return evalTests(req, res);
    } catch (IOException | ServletException e) {
        e.printStackTrace();
        return "Error on upload file";
    }
}

From source file:com.twitter.heron.apiserver.utils.FileHelper.java

private static void addFileToArchive(TarArchiveOutputStream archiveOutputStream, File file, String base)
        throws IOException {
    final File absoluteFile = file.getAbsoluteFile();
    final String entryName = base + file.getName();
    final TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(file, entryName);
    archiveOutputStream.putArchiveEntry(tarArchiveEntry);

    if (absoluteFile.isFile()) {
        Files.copy(file.toPath(), archiveOutputStream);
        archiveOutputStream.closeArchiveEntry();
    } else {/* w ww  . jav  a 2  s. c o  m*/
        archiveOutputStream.closeArchiveEntry();
        if (absoluteFile.listFiles() != null) {
            for (File f : absoluteFile.listFiles()) {
                addFileToArchive(archiveOutputStream, f, entryName + "/");
            }
        }
    }
}

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

@Override
public FileVisitResult preVisitDirectory(Path file, BasicFileAttributes attrs) throws IOException {
    // Copy directory
    Path newDir = target.resolve(source.relativize(file));
    try {/*ww  w  . j a  v  a2 s  .  c  o  m*/
        Files.copy(file, newDir);
    } catch (FileAlreadyExistsException ex) {
        // Set directory empty
        FileUtils.cleanDirectory(newDir.toFile());
    }
    return FileVisitResult.CONTINUE;
}

From source file:com.digitalpetri.opcua.raspberrypi.PiServer.java

private void configureLogback() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {//from  w  w w  .j  a v  a 2s . co  m
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        context.reset();

        System.out.println(System.getProperty("user.dir"));

        File logbackXml = new File("../config/logback.xml");

        if (!logbackXml.exists()) {
            InputStream is = getClass().getClassLoader().getResourceAsStream("logback.xml");
            Files.copy(is, logbackXml.toPath());
        }

        configurator.doConfigure(logbackXml);
    } catch (Exception e) {
        System.err.println("Error configuring logback." + e);
    }

    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}

From source file:fr.duminy.jbackup.core.archive.Decompressor.java

public void decompress(Path archive, Path targetDirectory, TaskListener listener, Cancellable cancellable)
        throws ArchiveException {
    if (listener != null) {
        try {/*from   www.  j a  v  a 2  s . c  om*/
            listener.totalSizeComputed(Files.size(archive));
        } catch (IOException ioe) {
            throw new ArchiveException(ioe);
        }
    }

    targetDirectory = (targetDirectory == null) ? Paths.get(".") : targetDirectory;
    if (!Files.exists(targetDirectory)) {
        throw new IllegalArgumentException(
                String.format("The target directory '%s' doesn't exist.", targetDirectory));
    }

    MutableLong processedSize = new MutableLong();

    try (InputStream archiveStream = Files.newInputStream(archive);
            ArchiveInputStream input = factory.create(archiveStream)) {
        ArchiveInputStream.Entry entry = getNextEntryIfNotCancelled(input, cancellable);
        while (entry != null) {
            InputStream entryStream = createCountingInputStream(listener, processedSize, entry.getInput());
            try {
                Path file = targetDirectory.resolve(entry.getName());
                Files.createDirectories(file.getParent());
                Files.copy(entryStream, file);
            } finally {
                entry.close();
            }

            entry = getNextEntryIfNotCancelled(input, cancellable);
        }
    } catch (IOException e) {
        throw new ArchiveException(e);
    } catch (Exception e) {
        throw new ArchiveException(e);
    }
}