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.facebook.buck.step.fs.ZstdStepTest.java

@Test
public void testZstdStep() throws Exception {
    Path sourceFileOriginal = TestDataHelper.getTestDataScenario(this, "compression_test").resolve("step.data");
    Path sourceFile = tmp.newFile("step.data").toPath();
    Files.copy(sourceFileOriginal, sourceFile, StandardCopyOption.REPLACE_EXISTING);
    File destinationFile = tmp.newFile("step.data.zstd");

    ZstdStep step = new ZstdStep(TestProjectFilesystems.createProjectFilesystem(tmp.getRoot().toPath()),
            sourceFile, destinationFile.toPath());

    ExecutionContext context = TestExecutionContext.newInstance();

    assertEquals(0, step.execute(context).getExitCode());

    ByteSource original = PathByteSource.asByteSource(sourceFileOriginal);
    ByteSource decompressed = new ByteSource() {
        @Override//ww w .  jav  a2 s . com
        public InputStream openStream() throws IOException {
            return new ZstdCompressorInputStream(new FileInputStream(destinationFile));
        }
    };

    assertFalse(Files.exists(sourceFile));
    assertTrue("Decompressed file must be identical to original.", original.contentEquals(decompressed));
}

From source file:nl.tudelft.graphalytics.granula.logging.GangliaLogger.java

private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException {
    if (sourceFolder.isDirectory()) {
        if (!destinationFolder.exists()) {
            destinationFolder.mkdir();//from   w ww. j a va 2  s.co m
        }

        //Get all files from source directory
        String files[] = sourceFolder.list();

        //Iterate over all files and copy them to destinationFolder one by one
        for (String file : files) {
            File srcFile = new File(sourceFolder, file);
            File destFile = new File(destinationFolder, file);

            //Recursive function call
            copyFolder(srcFile, destFile);
        }
    } else {
        Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
}

From source file:de.yaio.services.metaextract.server.extractor.TesseractExtractor.java

@Override
public String extractText(final InputStream input, final String fileName, final String lang)
        throws IOException, ExtractorException {
    File tmpFile;//from www  . ja  va2s .com
    tmpFile = File.createTempFile("metaextractor", "." + FilenameUtils.getExtension(fileName));
    tmpFile.deleteOnExit();
    Files.copy(input, tmpFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
    return this.extractText(tmpFile, lang);
}

From source file:com.javacreed.api.secureproperties.spring.SpringPropertiesTest.java

@Test
public void test() throws IOException {

    final String[] configurations = { "test-configuration-1.xml", "test-configuration-2.xml",
            "test-configuration-3.xml", "test-configuration-4.xml", "test-configuration-5.xml",
            /* "test-configuration-6.xml" */ };

    /*/* ww  w.jav a  2  s.c om*/
     * The source properties file that contains the plain text password and the target properties file from where the
     * configuration reads the properties
     */
    final File source = new File("src/test/resources/samples/properties/file.001.properties");
    final File target = new File("target/samples/properties/file.001.properties");
    target.getParentFile().mkdirs();

    for (final String configuration : configurations) {

        // Copy the properties file before the test
        Files.copy(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);

        for (int i = 0; i < 3; i++) {
            try (ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                    "/spring/" + configuration)) {
                // Check all three properties
                Assert.assertEquals("Albert",
                        applicationContext.getBeanFactory().resolveEmbeddedValue("${name}"));
                Assert.assertEquals("Somewhere in Malta",
                        applicationContext.getBeanFactory().resolveEmbeddedValue("${address}"));
                Assert.assertEquals("my long secret password",
                        applicationContext.getBeanFactory().resolveEmbeddedValue("${password}"));

                // Make sure that the password was encoded
                final List<String> lines = Files.readAllLines(target.toPath(), Charset.forName("UTF-8"));
                Assert.assertEquals(4, lines.size());
                Assert.assertEquals("# This is a simple properties file", lines.get(0));
                Assert.assertEquals("name=Albert", lines.get(1));
                Assert.assertEquals("address=Somewhere in Malta", lines.get(2));
                Assert.assertTrue(lines.get(3).startsWith("password={enc}"));
                Assert.assertFalse(lines.get(3).contains("my long secret password"));
            }
        }
    }
}

From source file:org.apache.gobblin.hive.avro.HiveAvroSerDeManagerTest.java

@BeforeClass
public void setUp() throws IOException {
    FileSystem fs = FileSystem.getLocal(new Configuration());
    this.testBasePath = new Path("testdir");
    fs.delete(this.testBasePath, true);
    fs.delete(this.testBasePath, true);

    fs.mkdirs(this.testBasePath);

    Files.copy(this.getClass().getResourceAsStream("/test-hive-table/hive-test.avro"),
            Paths.get(this.testBasePath.toString(), "hive-test.avro"), StandardCopyOption.REPLACE_EXISTING);
}

From source file:io.lavagna.service.ExportImportServiceTest.java

@Test
public void testImportAndExport() throws IOException {
    Path tmp = Files.createTempFile(null, null);
    try (InputStream is = new ClassPathResource("io/lavagna/export2.zip").getInputStream()) {
        Files.copy(is, tmp, StandardCopyOption.REPLACE_EXISTING);
        exportImportService.importData(false, tmp);

        // TODO additional checks

        exportImportService.exportData(new ByteArrayOutputStream());
    } finally {//w  w w. ja  va 2s .  co  m
        if (tmp != null) {
            Files.deleteIfExists(tmp);
        }
    }

}

From source file:ch.ledcom.jpreseed.web.TemporaryPreseedStore.java

public void addPreseeds(Collection<MultipartFile> preseeds) throws IOException {
    for (MultipartFile multipartFile : preseeds) {
        String name = multipartFile.getName();
        logger.debug("Adding pressed [{}] to preseed store.", name);
        Path preseed = tempDir.resolve(name);
        preseedPaths.add(preseed);/*  w w w. j  ava2 s  .  co m*/
        try (InputStream in = multipartFile.getInputStream()) {
            Files.copy(in, preseed, REPLACE_EXISTING);
        }
    }
}

From source file:com.xiaomi.linden.hadoop.indexing.LindenMapredTest.java

@Test
public void TestMapper() throws IOException {
    try {/*from   w w  w .ja v  a2 s .  c om*/
        String propertiesFilePath = LindenMapredTest.class.getClassLoader().getResource("linden.properties")
                .getFile();
        Files.copy(new File(propertiesFilePath).toPath(), Paths.get("lindenProperties"),
                StandardCopyOption.REPLACE_EXISTING);
        String schemaFilePath = LindenMapredTest.class.getClassLoader().getResource("schema.xml").getFile();
        Files.copy(new File(schemaFilePath).toPath(), Paths.get("lindenSchema"),
                StandardCopyOption.REPLACE_EXISTING);
        String json = "{\"id\":0,\"groupid\":\"0\",\"tags\":\"hybrid,leather,moon-roof,reliable\",\"category\":\"compact\",\"mileage\":14900,\"price\":7500,\"contents\":\"yellow compact hybrid leather moon-roof reliable u.s.a. florida tampa asian acura 1.6el \",\"color\":\"yellow\",\"year\":1994,\"makemodel\":\"asian/acura/1.6el\",\"city\":\"u.s.a./florida/tampa\"}";
        mDriver.withInput(new LongWritable(1L), new Text(json.getBytes()));
        mDriver.run();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    } finally {
        FileUtils.deleteQuietly(Paths.get("lindenProperties").toFile());
        FileUtils.deleteQuietly(Paths.get("lindenSchema").toFile());
    }
}

From source file:com.skynetcomputing.skynetclient.WorkManagerTest.java

/**
 * Test of start method, of class WorkManager.
 *
 * @throws java.io.IOException/*www. j av a2s  .c o  m*/
 * @throws java.lang.InterruptedException
 */
@Test
public void testStart() throws IOException, InterruptedException {
    IConnectionMgr conn = new IConnectionMgr() {
        @Override
        public void sendFile(File aFile) {
            try {
                Files.copy(aFile.toPath(), new File(LOCAL_INPUT_DIR + aFile.getName()).toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                Logger.getLogger(WorkManagerTest.class.getName()).log(Level.SEVERE, "Error sending file", ex);
            }
        }

        @Override
        public void notifyJarOKNOK(boolean isOK) throws IOException {
            assertTrue("Checking Jar presence", isOK);
        }

        @Override
        public void notifyTaskCompleted() throws IOException {
            Logger.getLogger(WorkManagerTest.class.getName()).log(Level.INFO, "Task Completed");
            synchronized (isRunning) {
                isRunning.set(false);
                isRunning.notifyAll();
            }
        }

        @Override
        public void start(InetSocketAddress serverAddress) {
            System.out.println("Fake start listening..");
        }

        @Override
        public boolean isSendingFiles() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void notifyTaskStarting() throws IOException {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    };

    WorkManager workMgr = new WorkManager(conn, ROOT_DIR);
    // Read only, should not be used for saving files
    PersistenceManager persistMgr = new PersistenceManager(ROOT_DIR);

    File testDir = new File(MANDELTASK_DIR);
    File jobJar = FileUtils.listFiles(testDir, new String[] { "jar" }, false).iterator().next();
    workMgr.onJarReceived(jobJar);
    File localDir = new File(LOCAL_INPUT_DIR);
    FileUtils.deleteDirectory(localDir);
    localDir.mkdirs();
    for (File f : testDir.listFiles()) {
        Files.copy(f.toPath(), new File(LOCAL_INPUT_DIR + f.getName()).toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    }

    for (int i = 1; i <= 4; i++) {
        isRunning.getAndSet(true);
        File taskJson = new File(localDir, i + ".task");
        File jobData = new File(localDir, i + ".data");

        workMgr.onTaskReceived(taskJson);
        workMgr.onDataReceived(jobData);

        synchronized (isRunning) {
            while (isRunning.get()) {
                isRunning.wait();
            }
        }
    }

    isRunning.getAndSet(true);

    File combineTaskFile = new File(localDir, "20" + SrzTask.EXT);
    workMgr.onTaskReceived(combineTaskFile);

    SrzTask combineTask = persistMgr.readTaskFile(combineTaskFile);
    for (int id : combineTask.getDependencies()) {
        workMgr.onDataReceived(new File(localDir, id + SrzData.EXT));
    }

    synchronized (isRunning) {
        while (isRunning.get()) {
            isRunning.wait();
        }
    }

    Logger.getLogger(WorkManagerTest.class.getName()).log(Level.INFO, "Test Finished");
}

From source file:JMeterProcessing.JMeterPropertiesGenerator.java

private static void generatePropertiesFile(Map<String, Long> idValuesMap) throws IOException {
    String propertiesOutputDir = System.getProperty("properties.output.dir");
    File original = new File(propertiesOutputDir + "/testray.jmeter.full.depth.properties");
    File generated = new File(propertiesOutputDir + "/testray.jmeter.properties");

    Files.copy(original.toPath(), generated.toPath(), StandardCopyOption.REPLACE_EXISTING);

    try (BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(generated, true), "utf-8"))) {

        printProperties(writer, idValuesMap);

        writer.flush();/*from   www  . j a  va 2  s. c o m*/
    }
}