Example usage for java.nio.file Files write

List of usage examples for java.nio.file Files write

Introduction

In this page you can find the example usage for java.nio.file Files write.

Prototype

public static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)
        throws IOException 

Source Link

Document

Write lines of text to a file.

Usage

From source file:org.epics.archiverappliance.etl.ZeroByteFilesTest.java

public void testZeroByteFilesInSource() throws Exception {
    // Create zero byte files in the ETL source; since this is a daily partition, we need something like so sine:2016_03_31.pb
    String pvName = ConfigServiceForTests.ARCH_UNIT_TEST_PVNAME_PREFIX + "ETL_testZeroSrc";
    VoidFunction zeroByteGenerator = () -> {
        for (int day = 2; day < 10; day++) {
            Path zeroSrcPath = Paths.get(etlSrc.getRootFolder(),
                    pvNameToKeyConverter.convertPVNameToKey(pvName)
                            + TimeUtils.getPartitionName(TimeUtils.getCurrentEpochSeconds() - day * 86400,
                                    PartitionGranularity.PARTITION_DAY)
                            + PlainPBStoragePlugin.PB_EXTENSION);
            logger.info("Creating zero byte file " + zeroSrcPath);
            Files.write(zeroSrcPath, new byte[0], StandardOpenOption.CREATE);
        }//  w w w  . j a v  a2  s. c om
    };
    runETLAndValidate(pvName, zeroByteGenerator);
}

From source file:MainServer.java

public void run() {
    //continue to check and remove expired peers

    //set target time (2 days)
    long target_time = 172800;

    for (;;) {/*from w  ww .jav  a2 s . co  m*/
        //find the current time
        long current_time = System.currentTimeMillis() / 1000;

        //get all peers and check their last seen time
        for (String x : WriteToFiles.peers_timer.keySet()) {
            long tyme = WriteToFiles.peers_timer.get(x);
            if (current_time - tyme >= delay) {
                WriteToFiles.peers_timer.remove(x);
                WriteToFiles.peers_map.remove(x);
            }
        }

        //update the peers database
        String[] new_content = new String[WriteToFiles.peers_map.size()];
        int i = 0;
        for (String y : WriteToFiles.peers_map.keySet()) {
            new_content[i] = y + " " + WriteToFiles.peers_map.get(y);
            i++;
        }
        try {
            Files.write(Paths.get(path), Arrays.asList(new_content), utf8);
            //Thread.sleep(3600000); //sleep for 1 hour
            Thread.sleep(1000);
        } catch (Exception efe) {
        }

    }
}

From source file:org.dmb.trueprice.utils.internal.FileUtils.java

/**
     * Write FID's attachements on server
     * /* www  . j ava2  s.  co m*/
     * @param fileName - Nom du fichier joint
     * @param fileContent - InputStream contenant le coprs du fichier
     * @param targetFolder - Dossier o crire le fichier
     */
//    public static void writeFile(String fileName,InputStream fileContent, String targetFolder) throws IOException{
public static void writeFile(String fileName, byte[] bytes, String targetFolder) throws IOException {

    //        try {

    Files.write(Paths.get(targetFolder + File.separator + fileName), bytes, StandardOpenOption.WRITE
    //                , StandardOpenOption.CREATE_NEW
    );

    //        } catch ( e) {
    //            logger.error("IOException writing attachment on disk : " + e.getMessage());
    //        }
}

From source file:example.UserGuideTest.java

public static void writeGraph(Graph graph, Path graphFile) throws Exception {
    Stream<CharSequence> stream = graph.getTriples().map(UserGuideTest::tripleAsString);
    Files.write(graphFile, stream::iterator, StandardCharsets.UTF_8);
}

From source file:com.hpe.caf.worker.testing.validation.ReferenceDataValidator.java

@Override
public boolean isValid(Object testedPropertyValue, Object validatorPropertyValue) {

    if (testedPropertyValue == null && validatorPropertyValue == null)
        return true;

    ObjectMapper mapper = new ObjectMapper();

    ContentFileTestExpectation expectation = mapper.convertValue(validatorPropertyValue,
            ContentFileTestExpectation.class);

    ReferencedData referencedData = mapper.convertValue(testedPropertyValue, ReferencedData.class);

    InputStream dataStream;/*w  w w . j av  a2  s . co m*/

    if (expectation.getExpectedContentFile() == null && expectation.getExpectedSimilarityPercentage() == 0) {
        return true;
    }

    try {
        System.out.println("About to retrieve content for " + referencedData.toString());
        dataStream = ContentDataHelper.retrieveReferencedData(dataStore, codec, referencedData);
        System.out.println("Finished retrieving content for " + referencedData.toString());
    } catch (DataSourceException e) {
        e.printStackTrace();
        System.err.println("Failed to acquire referenced data.");
        e.printStackTrace();
        TestResultHelper.testFailed("Failed to acquire referenced data. Exception message: " + e.getMessage(),
                e);
        return false;
    }
    try {
        String contentFileName = expectation.getExpectedContentFile();
        Path contentFile = Paths.get(contentFileName);
        if (Files.notExists(contentFile) && !Strings.isNullOrEmpty(testSourcefileBaseFolder)) {
            contentFile = Paths.get(testSourcefileBaseFolder, contentFileName);
        }

        if (Files.notExists(contentFile)) {
            contentFile = Paths.get(testDataFolder, contentFileName);
        }

        byte[] expectedFileBytes = Files.readAllBytes(contentFile);

        if (expectation.getComparisonType() == ContentComparisonType.TEXT) {

            String actualText = IOUtils.toString(dataStream, StandardCharsets.UTF_8);
            String expectedText = new String(expectedFileBytes, StandardCharsets.UTF_8);

            if (expectation.getExpectedSimilarityPercentage() == 100) {
                boolean equals = actualText.equals(expectedText);
                if (!equals) {
                    String message = "Expected and actual texts were different.\n\n*** Expected Text ***\n"
                            + expectedText + "\n\n*** Actual Text ***\n" + actualText;
                    System.err.println(message);
                    if (throwOnValidationFailure)
                        TestResultHelper.testFailed(message);
                    return false;
                }
                return true;
            }

            double similarity = ContentComparer.calculateSimilarityPercentage(expectedText, actualText);

            System.out.println("Compared text similarity:" + similarity + "%");

            if (similarity < expectation.getExpectedSimilarityPercentage()) {
                String message = "Expected similarity of " + expectation.getExpectedSimilarityPercentage()
                        + "% but actual similarity was " + similarity + "%";
                System.err.println(message);
                if (throwOnValidationFailure)
                    TestResultHelper.testFailed(message);
                return false;
            }
        } else {
            byte[] actualDataBytes = IOUtils.toByteArray(dataStream);
            boolean equals = Arrays.equals(actualDataBytes, expectedFileBytes);
            if (!equals) {
                String actualContentFileName = contentFile.getFileName() + "_actual";
                Path actualFilePath = Paths.get(contentFile.getParent().toString(), actualContentFileName);
                Files.deleteIfExists(actualFilePath);
                Files.write(actualFilePath, actualDataBytes, StandardOpenOption.CREATE);
                String message = "Data returned was different than expected for file: " + contentFileName
                        + "\nActual content saved in file: " + actualFilePath.toString();
                System.err.println(message);
                if (throwOnValidationFailure)
                    TestResultHelper.testFailed(message);
                return false;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        TestResultHelper.testFailed("Error while processing reference data! " + e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:org.eclipse.vorto.remoterepository.internal.dao.FilesystemModelDAO.java

@Override
public ModelView saveModel(ModelContent modelContent) {

    ModelId mID = modelContent.getModelId();
    ModelView mv = ModelFactory.newModelView(mID, "Newly Added Model, ....");
    Path dirToSave = this.resolveDirectoryPathToModel(mID);
    Path fileToSave = this.resolvePathToModel(mID);

    try {//from w w w.  jav a  2s.c  o m
        if (!Files.exists(dirToSave)) {
            Files.createDirectories(dirToSave);
        }

        if (!Files.exists(fileToSave)) {
            Files.createFile(fileToSave);
        } else {
            Files.deleteIfExists(fileToSave);
        }

        Files.write(fileToSave, modelContent.getContent(), StandardOpenOption.TRUNCATE_EXISTING);
        return mv;
    } catch (IOException e) {
        throw new RuntimeException("An I/O error was thrown while saving new model file: " + mID.toString(), e);
    }
}

From source file:org.ballerinalang.test.packaging.ImportModuleTestCase.java

/**
 * Importing installed modules in test sources.
 *
 * @throws BallerinaTestException When an error occurs executing the command.
 *//*from   w w w  . java2 s  . c  om*/
@Test(description = "Test importing installed modules in test sources")
public void testResolveImportsFromInstalledModulesInTests() throws BallerinaTestException, IOException {
    Path projPath = tempProjectDirectory.resolve("thirdProj");
    Files.createDirectories(projPath);

    FileUtils.copyDirectory(
            Paths.get((new File("src/test/resources/import-test-in-cache")).getAbsolutePath()).toFile(),
            projPath.toFile());
    Files.createDirectories(projPath.resolve(".ballerina"));

    // ballerina install abc
    balClient.runMain("install", new String[] { "mod2" }, envVariables, new String[] {}, new LogLeecher[] {},
            projPath.toString());

    // Delete module 'abc' from the project
    PackagingTestUtils.deleteFiles(projPath.resolve("mod2"));
    PackagingTestUtils.deleteFiles(projPath.resolve(".ballerina").resolve("repo"));

    // Rename org-name to "natasha" in Ballerina.toml
    Path tomlFilePath = projPath.resolve("Ballerina.toml");
    String content = "[project]\norg-name = \"natasha\"\nversion = \"1.0.0\"\n";
    Files.write(tomlFilePath, content.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);

    // Module fanny/mod2 will be picked from home repository since it was installed before
    balClient.runMain("build", new String[] {}, envVariables, new String[] {}, new LogLeecher[] {},
            projPath.toString());

    Assert.assertTrue(Files.exists(projPath.resolve(".ballerina").resolve("repo").resolve("natasha")
            .resolve("mod1").resolve("1.0.0").resolve("mod1.zip")));

    LogLeecher sLeecher = new LogLeecher("Hello!! I got a message from a cached repository module --> 100");
    balClient.runMain("test", new String[] { "mod1" }, envVariables, new String[] {},
            new LogLeecher[] { sLeecher }, projPath.toString());
    sLeecher.waitForText(3000);
}

From source file:com.streamsets.pipeline.stage.origin.logtail.TestFileTailSource.java

@Test
public void testTailLogSameFilesInSameDir() throws Exception {
    File testDataDir1 = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(testDataDir1.mkdirs());
    Files.write(new File(testDataDir1, "log1.txt").toPath(), Arrays.asList("Hello"), UTF8);
    Files.write(new File(testDataDir1, "log1.txt").toPath(), Arrays.asList("Hola"), UTF8);

    FileInfo fileInfo1 = new FileInfo();
    fileInfo1.fileFullPath = testDataDir1.getAbsolutePath() + "/log1.txt";
    fileInfo1.fileRollMode = FileRollMode.REVERSE_COUNTER;
    fileInfo1.firstFile = "";
    fileInfo1.patternForToken = "";
    FileInfo fileInfo2 = new FileInfo();
    fileInfo2.fileFullPath = testDataDir1.getAbsolutePath() + "/log1.txt";
    fileInfo2.fileRollMode = FileRollMode.REVERSE_COUNTER;
    fileInfo2.firstFile = "";
    fileInfo2.patternForToken = "";

    FileTailConfigBean conf = new FileTailConfigBean();
    conf.dataFormat = DataFormat.TEXT;//from  w w  w  .  jav a 2s  .  c o m
    conf.multiLineMainPattern = "";
    conf.batchSize = 25;
    conf.maxWaitTimeSecs = 1;
    conf.fileInfos = Arrays.asList(fileInfo1, fileInfo2);
    conf.postProcessing = PostProcessingOptions.NONE;
    conf.dataFormatConfig.textMaxLineLen = 1024;

    FileTailSource source = new FileTailSource(conf, SCAN_INTERVAL);
    SourceRunner runner = new SourceRunner.Builder(FileTailDSource.class, source).addOutputLane("lane")
            .addOutputLane("metadata").build();
    Assert.assertTrue(!runner.runValidateConfigs().isEmpty());
    Assert.assertTrue(runner.runValidateConfigs().get(0).toString().contains("TAIL_04"));
}

From source file:com.adeptj.runtime.server.Server.java

private void createServerConfFile() {
    if (!Environment.isServerConfFileExists()) {
        try (InputStream stream = this.getClass().getResourceAsStream("/reference.conf")) {
            Files.write(Paths.get(USER_DIR, Constants.DIR_ADEPTJ_RUNTIME, Constants.DIR_DEPLOYMENT,
                    Constants.SERVER_CONF_FILE), IOUtils.toBytes(stream), StandardOpenOption.CREATE);
        } catch (IOException ex) {
            LOGGER.error("Exception while creating server conf file!!", ex);
        }//w  w w. j  ava  2  s. co  m
    }
}

From source file:org.apache.kudu.client.MiniKdc.java

private void createKrb5Conf() throws IOException {
    List<String> contents = ImmutableList.of("[logging]", "   kdc = FILE:/dev/stderr",

            "[libdefaults]", "   default_realm = " + options.realm, "   dns_lookup_kdc = false",
            "   dns_lookup_realm = false", "   forwardable = true", "   renew_lifetime = 7d",
            "   ticket_lifetime = 24h",

            // Disable aes256, since Java does not support it without JCE, see
            // https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/jgss-features.html
            "   default_tkt_enctypes = aes128-cts des3-cbc-sha1",
            "   default_tgs_enctypes = aes128-cts des3-cbc-sha1",
            "   permitted_enctypes = aes128-cts des3-cbc-sha1",

            // In miniclusters, we start daemons on local loopback IPs that
            // have no reverse DNS entries. So, disable reverse DNS.
            "   rdns = false", "   ignore_acceptor_hostname = true",

            "[realms]", options.realm + " = {", "   kdc = 127.0.0.1:" + options.port, "}");

    Files.write(options.dataRoot.resolve("krb5.conf"), contents, Charsets.UTF_8);
}