Example usage for java.nio.file Files readAllLines

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

Introduction

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

Prototype

public static List<String> readAllLines(Path path, Charset cs) throws IOException 

Source Link

Document

Read all lines from a file.

Usage

From source file:com.spotify.docker.BuildMojoTest.java

public void testBuildWithDockerVolumes() throws Exception {
    final File pom = getTestFile("src/test/resources/pom-build-docker-volumes.xml");
    assertNotNull("Null pom.xml", pom);
    assertTrue("pom.xml does not exist", pom.exists());

    final BuildMojo mojo = setupMojo(pom);
    final DockerClient docker = mock(DockerClient.class);

    mojo.execute(docker);//from  w  ww.ja va2s  .c  o m
    verify(docker).build(eq(Paths.get("target/docker")), eq("busybox"), any(AnsiProgressHandler.class));
    assertFilesCopied();

    assertEquals("wrong dockerfile contents", GENERATED_DOCKERFILEVOLUME,
            Files.readAllLines(Paths.get("target/docker/Dockerfile"), UTF_8));
}

From source file:eu.diversify.disco.experiments.testing.Tester.java

private String readContentOf(File readme) throws IOException {
    final StringBuffer buffer = new StringBuffer();
    for (String line : Files.readAllLines(readme.toPath(), Charset.defaultCharset())) {
        buffer.append(line);/*from  w  ww .  j ava2s  .c om*/
    }
    return buffer.toString();
}

From source file:alluxio.cli.ConfigurationDocGeneratorTest.java

@Test
public void checkCSVFile() throws Exception {
    if (mFileType != TYPE.CSV) {
        return;/* ww w  .  j a v a  2 s.c o m*/
    }
    Collection<PropertyKey> defaultKeys = new ArrayList<>();
    PropertyKey pKey = mTestConf.getFirst();
    defaultKeys.add(pKey);

    ConfigurationDocGenerator.writeCSVFile(defaultKeys, mLocation);
    String filePath = PathUtils.concatPath(mLocation, mTestConf.getSecond());
    Path p = Paths.get(filePath);
    assertTrue(Files.exists(p));

    //assert file contents
    List<String> userFile = Files.readAllLines(p, StandardCharsets.UTF_8);
    String defaultValue = Configuration.get(pKey);
    checkFileContents(String.format("%s,\"%s\"", pKey, defaultValue), userFile, mFileType);
}

From source file:net.estinet.gFeatures.Feature.gRanks.gRanks.java

public static List<String> getPermsFile(File f) throws IOException {
    List<String> perms = Files.readAllLines(Paths.get(f.getPath()), StandardCharsets.UTF_8);
    for (int i = 0; i < perms.size(); i++) {
        perms.set(i, perms.get(i).replace("\r", ""));
        if (perms.get(i).equals("")) {
            if (i != 0)
                i--;//from   w  ww .jav a 2  s .  c o m
            perms.remove(i);
        }
    }
    return perms;
}

From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java

@Test
public void testKeyOverrides() throws Exception {
    final Map<String, String> keyOverrides = new HashMap<>();
    keyOverrides.put("timestamp", "dateTime");
    keyOverrides.put("sequence", "seq");
    final Map<String, String> metaData = new LinkedHashMap<>();
    metaData.put("test-key-1", "test-value-1");
    metaData.put("key-no-value", null);
    // Configure the subsystem
    configure(keyOverrides, metaData, true);

    final String msg = "Logging test: JsonFormatterTestCase.defaultLoggingTest";
    final Map<String, String> params = new LinkedHashMap<>();
    // Indicate we need an exception logged
    params.put(LoggingServiceActivator.LOG_EXCEPTION_KEY, "true");
    // Add an NDC value
    params.put(LoggingServiceActivator.NDC_KEY, "test.ndc.value");
    // Add some map entries for MDC values
    params.put("mdcKey1", "mdcValue1");
    params.put("mdcKey2", "mdcValue2");

    final List<String> expectedKeys = createDefaultKeys();
    expectedKeys.remove("timestamp");
    expectedKeys.remove("sequence");
    expectedKeys.addAll(keyOverrides.values());
    expectedKeys.addAll(metaData.keySet());
    expectedKeys.add("exception");
    expectedKeys.add("stackTrace");
    expectedKeys.add("sourceFileName");
    expectedKeys.add("sourceMethodName");
    expectedKeys.add("sourceClassName");
    expectedKeys.add("sourceLineNumber");
    expectedKeys.add("sourceModuleVersion");
    expectedKeys.add("sourceModuleName");

    final int statusCode = getResponse(msg, params);
    Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);

    // Validate each line
    for (String s : Files.readAllLines(logFile, StandardCharsets.UTF_8)) {
        if (s.trim().isEmpty())
            continue;
        try (JsonReader reader = Json.createReader(new StringReader(s))) {
            final JsonObject json = reader.readObject();
            validateDefault(json, expectedKeys, msg);

            // Timestamp should have been renamed to dateTime
            Assert.assertNull("Found timestamp entry in " + s, json.get("timestamp"));

            // Sequence should have been renamed to seq
            Assert.assertNull("Found sequence entry in " + s, json.get("sequence"));

            // Validate MDC
            final JsonObject mdcObject = json.getJsonObject("mdc");
            Assert.assertEquals("mdcValue1", mdcObject.getString("mdcKey1"));
            Assert.assertEquals("mdcValue2", mdcObject.getString("mdcKey2"));

            // Validate the meta-data
            Assert.assertEquals("test-value-1", json.getString("test-key-1"));
            Assert.assertEquals("Expected a null type but got " + json.get("key-no-value"),
                    JsonValue.ValueType.NULL, json.get("key-no-value").getValueType());

            validateStackTrace(json, true, true);
        }/*w ww . j  ava  2 s  .c  o  m*/
    }
}

From source file:org.apache.taverna.download.impl.DownloadManagerImpl.java

private String downloadHash(URI source) throws DownloadException {
    try {/*from   w  w w.  ja va 2s.  c o m*/
        // We want to handle http/https with HTTPClient
        if (source.getScheme().equalsIgnoreCase("http") || source.getScheme().equalsIgnoreCase("https")) {
            logger.info("Downloading checksum " + source);
            return Request.Get(source).userAgent(getUserAgent()).connectTimeout(TIMEOUT).socketTimeout(TIMEOUT)
                    .execute().returnContent().asString(StandardCharsets.ISO_8859_1);
        } else {
            // Try as a supported Path, e.g. file: or relative path
            try {
                Path path = Paths.get(source);
                return Files.readAllLines(path, StandardCharsets.ISO_8859_1).get(0);
            } catch (FileSystemNotFoundException e) {
                throw new DownloadException("Unsupported URL scheme: " + source.getScheme());
            }
        }
    } catch (IOException e) {
        throw new DownloadException(String.format("Error downloading %1$s", source), e);
    }
}

From source file:com.kakao.hbase.manager.command.ExportKeysTest.java

@Test
public void testRegex() throws Exception {
    String outputFile = "exportkeys_test.keys";

    try {//w  w  w. j a v  a 2  s .  c o m
        String splitPoint = "splitpoint";
        splitTable(splitPoint.getBytes());
        String tableName2 = createAdditionalTable(tableName + "2");
        splitTable(tableName2, splitPoint.getBytes());

        String tableNameRegex = tableName + ".*";
        String[] argsParam = { "zookeeper", tableNameRegex, outputFile };
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        ExportKeys command = new ExportKeys(admin, args);

        waitForSplitting(2);
        waitForSplitting(tableName2, 2);
        command.run();

        List<Triple<String, String, String>> results = new ArrayList<>();
        for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

            String[] split = keys.split(ExportKeys.DELIMITER);
            results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
        }
        assertEquals(4, results.size());
    } finally {
        Files.delete(Paths.get(outputFile));
    }
}

From source file:rapture.series.file.FileSeriesStore.java

/**
 * Returns a sorted series//from  ww  w  .ja  v  a  2s  .c  o m
 *
 * @param direction
 *            true for verbatim, false for reverse order.
 * @return
 */
protected Collection<SeriesValue> readSeriesSorted(String key, boolean direction) {
    File seriesFile = FileRepoUtils.makeGenericFile(parentDir, key);
    if (!seriesFile.isFile())
        return new ArrayList<>();
    TreeSet<SeriesValue> series = new TreeSet<>((direction) ? forwards : backwards);
    try {
        List<String> lines = Files.readAllLines(seriesFile.toPath(), StandardCharsets.UTF_8);
        for (String line : lines) {
            char c = line.charAt(0);
            int i = line.indexOf(c, 1);
            String column = line.substring(1, i);
            byte[] bytes = line.substring(i + 1).getBytes();
            series.add(SeriesValueCodec.decode(column, bytes));
        }
        return series;
    } catch (IOException e) {
        log.debug(ExceptionToString.format(e));
    }
    return null;
}

From source file:alluxio.cli.ConfigurationDocGeneratorTest.java

@Test
public void checkYMLFile() throws Exception {
    if (mFileType != TYPE.YML) {
        return;//ww w .jav a2 s.  c o m
    }
    Collection<PropertyKey> defaultKeys = new ArrayList<>();
    PropertyKey pKey = mTestConf.getFirst();
    String description = pKey.getDescription();
    defaultKeys.add(pKey);

    ConfigurationDocGenerator.writeYMLFile(defaultKeys, mLocation);
    String filePath = PathUtils.concatPath(mLocation, mTestConf.getSecond());
    Path p = Paths.get(filePath);
    assertTrue(Files.exists(p));

    //assert file contents
    List<String> keyDescription = Files.readAllLines(p, StandardCharsets.UTF_8);
    String expected = pKey + ":\n  '" + description.replace("'", "''") + "'";
    checkFileContents(expected, keyDescription, mFileType);
}

From source file:ffdammit.SkyProcMain.java

public List<String> loadTextArray(String fileName) {
    try {/* w ww  .  j  a  v  a 2 s  . c om*/
        return Files.readAllLines(new File(fileName).toPath(), Charset.defaultCharset()).stream()
                .map(String::trim).distinct().collect(Collectors.toList());
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}