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.ibm.watson.app.qaclassifier.ScanLogs.java

public static void getBluemixLogs(String user, String password, String target, String org, String space,
        String app) throws Exception {
    CloudFoundryClient client;/*from ww w. ja v  a 2s.  c  o  m*/
    if (user == null || user.isEmpty()) {
        System.out.println("No username/password provided, using saved credentials");
        client = new CloudFoundryClient(new CloudCredentials(new TokensFile().retrieveToken(new URI(target))),
                new URL(target), org, space);
    } else {
        client = new CloudFoundryClient(new CloudCredentials(user, password), new URL(target), org, space);
    }

    client.openFile(app, 0, "logs/" + LOG_FILE, new ClientHttpResponseCallback() {
        @Override
        public void onClientHttpResponse(ClientHttpResponse clientHttpResponse) throws IOException {
            Path logDestination = Paths.get(LOG_FILE);
            if (Files.exists(logDestination)) {
                Files.delete(logDestination);
            }
            Files.copy(clientHttpResponse.getBody(), logDestination);
        }
    });
}

From source file:org.apache.druid.segment.loading.HdfsFileTimestampVersionFinderTest.java

@BeforeClass
public static void setupStatic() throws IOException {
    hdfsTmpDir = File.createTempFile("hdfsHandlerTest", "dir");
    if (!hdfsTmpDir.delete()) {
        throw new IOE("Unable to delete hdfsTmpDir [%s]", hdfsTmpDir.getAbsolutePath());
    }/*from  ww  w . j a  v  a 2s. c  o m*/
    conf = new Configuration(true);
    conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsTmpDir.getAbsolutePath());
    miniCluster = new MiniDFSCluster.Builder(conf).build();

    final File tmpFile = File.createTempFile("hdfsHandlerTest", ".data");
    tmpFile.delete();
    try {
        Files.copy(new ByteArrayInputStream(pathByteContents), tmpFile.toPath());
        try (OutputStream stream = miniCluster.getFileSystem().create(filePath)) {
            Files.copy(tmpFile.toPath(), stream);
        }
    } finally {
        tmpFile.delete();
    }
}

From source file:org.khmeracademy.btb.auc.pojo.service.impl.UploadImage_serviceimpl.java

@Override
public Image upload(int pro_id, List<MultipartFile> files) {
    Image uploadImage = new Image();
    if (files.isEmpty()) {

    } else {/*from   w  w  w  .ja va 2s. com*/

        //            if(folder=="" || folder==null)
        //                folder = "default";
        String UPLOAD_PATH = "/opt/project/default";
        String THUMBNAIL_PATH = "/opt/project/thumnail/";

        java.io.File path = new java.io.File(UPLOAD_PATH);
        java.io.File thum_path = new java.io.File(THUMBNAIL_PATH);
        if (!path.exists())
            path.mkdirs();
        if (!thum_path.exists()) {
            thum_path.mkdirs();
        }

        List<String> names = new ArrayList<>();
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            fileName = UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
            try {
                byte[] bytes = file.getBytes();
                Files.copy(file.getInputStream(), Paths.get(UPLOAD_PATH, fileName)); //copy path name to server
                try {
                    //TODO: USING THUMBNAILS TO RESIZE THE IMAGE

                    Thumbnails.of(UPLOAD_PATH + "/" + fileName).forceSize(640, 640).toFiles(thum_path,
                            Rename.NO_CHANGE);
                } catch (Exception ex) {
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(new File(THUMBNAIL_PATH + fileName)));
                    stream.write(bytes);
                    stream.close();
                }
                names.add(fileName); // add file name
                imRepo.upload(pro_id, fileName); // upload path to database
            } catch (Exception e) {

            }
        }
        uploadImage.setProjectPath("/resources/");
        uploadImage.setServerPath(UPLOAD_PATH);
        uploadImage.setNames(names);
        uploadImage.setMessage("File has been uploaded successfully!!!");
    }
    return uploadImage;
}

From source file:io.druid.storage.hdfs.HdfsDataSegmentPullerTest.java

@BeforeClass
public static void setupStatic() throws IOException {
    hdfsTmpDir = File.createTempFile("hdfsHandlerTest", "dir");
    if (!hdfsTmpDir.delete()) {
        throw new IOE("Unable to delete hdfsTmpDir [%s]", hdfsTmpDir.getAbsolutePath());
    }//from  w  ww.j  a  v  a 2s  . c  o  m
    conf = new Configuration(true);
    conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsTmpDir.getAbsolutePath());
    miniCluster = new MiniDFSCluster.Builder(conf).build();
    uriBase = miniCluster.getURI(0);

    final File tmpFile = File.createTempFile("hdfsHandlerTest", ".data");
    tmpFile.delete();
    try {
        Files.copy(new ByteArrayInputStream(pathByteContents), tmpFile.toPath());
        try (OutputStream stream = miniCluster.getFileSystem().create(filePath)) {
            Files.copy(tmpFile.toPath(), stream);
        }
    } finally {
        tmpFile.delete();
    }
}

From source file:io.druid.segment.loading.HdfsDataSegmentPullerTest.java

@BeforeClass
public static void setupStatic() throws IOException, ClassNotFoundException {
    hdfsTmpDir = File.createTempFile("hdfsHandlerTest", "dir");
    if (!hdfsTmpDir.delete()) {
        throw new IOE("Unable to delete hdfsTmpDir [%s]", hdfsTmpDir.getAbsolutePath());
    }//ww w.jav  a 2  s .co m
    conf = new Configuration(true);
    conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsTmpDir.getAbsolutePath());
    miniCluster = new MiniDFSCluster.Builder(conf).build();
    uriBase = miniCluster.getURI(0);

    final File tmpFile = File.createTempFile("hdfsHandlerTest", ".data");
    tmpFile.delete();
    try {
        Files.copy(new ByteArrayInputStream(pathByteContents), tmpFile.toPath());
        try (OutputStream stream = miniCluster.getFileSystem().create(filePath)) {
            Files.copy(tmpFile.toPath(), stream);
        }
    } finally {
        tmpFile.delete();
    }
}

From source file:org.bonitasoft.web.designer.controller.utils.HttpFile.java

/**
 * Write headers and content in the response
 *//*ww  w . j ava2  s  . c om*/
private static void writeFileInResponse(HttpServletResponse response, Path filePath, String mimeType,
        String contentDispositionType) throws IOException {
    response.setHeader("Content-Type", mimeType);
    response.setHeader("Content-Length", String.valueOf(filePath.toFile().length()));
    response.setHeader("Content-Disposition", new StringBuilder().append(contentDispositionType)
            .append("; filename=\"").append(filePath.getFileName()).append("\"").toString());
    response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
    try (OutputStream out = response.getOutputStream()) {
        Files.copy(filePath, out);
    }
}

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

@Put
public void putImage(Representation entity) {
    if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
        try {//from ww  w  .  j  a va2  s. c o  m
            DiskFileItemFactory factory = new DiskFileItemFactory();
            RestletFileUpload upload = new RestletFileUpload(factory);
            FileItemIterator fileIterator = upload.getItemIterator(entity);

            if (fileIterator.hasNext()) {
                FileItemStream fi = fileIterator.next();

                String name = fi.getName();

                File file = new File(dataDir, name);

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

                Files.copy(fi.openStream(), file.toPath());

                BuntataDatasource ds = dao.get(id);
                ds.setIcon(file.getName());
                dao.updateIcon(ds);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
    }
}

From source file:onl.area51.httpd.util.PathEntity.java

@Override
public void writeTo(final OutputStream outstream) throws IOException {
    Files.copy(file, outstream);
}

From source file:car_counter.processing.TestDefaultProcessor.java

@Test
public void testStoreMultipleVehicles() throws Exception {
    // Arrange// w w w.  j  a v a  2s.com
    DefaultProcessor processor = new DefaultProcessor(ini);
    Files.copy(Paths.get("test/data/21-20140504155125.avi"), incoming.resolve("21-20140504155125.avi"));

    // Act
    processor.processIncomingContents();

    // Assert
    String expected = "0 id=1 timestamp=1399182685000 initial_location=0 end_location=0 speed=null colour=null video_file=### \n";

    String contents = DatabaseTestUtils.getTableContents("detected_vehicles",
            ((SqliteStorage) processor.getStorage()).getConnection());
    contents = contents.replaceAll("video_file=[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
            "video_file=###");

    assertThat(contents, is(expected));
}