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:kmi.taa.core.SmallSetAnalyser.java

public void addLineids(Path path, String output) {
    StringBuilder builder = new StringBuilder();

    try {//  w ww .  j a va 2 s.  c  o m
        List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
        int i = 1;
        for (String l : lines) {
            builder.append(l + "\t" + i++);
            builder.append(System.lineSeparator());
        }
    } catch (IOException e) {

    }

    FileHelper.writeFile(builder.toString(), output, false);
}

From source file:org.apache.htrace.impl.TestDroppedSpans.java

/**
 * Test that we write to the dropped spans log when htraced is unreachable.
 */// www . ja  v a  2 s.com
@Test(timeout = 60000)
public void testSpansDroppedBecauseOfUnreachableHTraced() throws Exception {
    final String logPath = new File(tempDir.toFile(), "testSpansDroppedBecauseOfUnreachableHTraced")
            .getAbsolutePath();
    // Open a local socket.  We know that nobody is listening on this socket, so
    // all attempts to send to it will fail.
    final ServerSocket serverSocket = new ServerSocket(0);
    HTracedSpanReceiver rcvr = null;
    try {
        HTraceConfiguration conf = HTraceConfiguration.fromMap(new HashMap<String, String>() {
            {
                put(Conf.ADDRESS_KEY, "127.0.0.1:" + serverSocket.getLocalPort());
                put(TracerId.TRACER_ID_KEY, "testSpansDroppedBecauseOfUnreachableHTraced");
                put(Conf.DROPPED_SPANS_LOG_PATH_KEY, logPath);
                put(Conf.DROPPED_SPANS_LOG_MAX_SIZE_KEY, "78");
                put(Conf.CONNECT_TIMEOUT_MS_KEY, "1");
                put(Conf.IO_TIMEOUT_MS_KEY, "1");
                put(Conf.FLUSH_RETRY_DELAYS_KEY, "1,1");
            }
        });
        rcvr = new HTracedSpanReceiver(conf);
        rcvr.receiveSpan(new MilliSpan.Builder().begin(123).end(456).description("FooBar").build());
        HTracedSpanReceiver tmpRcvr = rcvr;
        rcvr = null;
        tmpRcvr.close();
        List<String> lines = Files.readAllLines(Paths.get(logPath), StandardCharsets.UTF_8);
        Assert.assertTrue(lines.size() >= 1);
        Assert.assertTrue(lines.get(0).contains("Failed to flush "));
    } finally {
        serverSocket.close();
        if (rcvr != null) {
            rcvr.close();
        }
    }
}

From source file:nu.mine.kino.assertionutils.TextAssertionLogic.java

private List<String> readText(Path path, Charset enc) {
    List<String> lines = null;
    try {//from  w w w . j  a v  a2  s .  c o  m
        lines = Files.readAllLines(path, enc);
    } catch (IOException e) {
        slogger.error("??????: {},({})", path, e.getMessage());
        slogger.error("", e);
        String message = "java.nio.charset.MalformedInputException: Input length = xx? \n???????"
                + "????????????????????"
                + "?????";
        slogger.error(message);
        fail(e.getMessage());
    }
    return lines;
}

From source file:io.mindmaps.graql.GraqlShell.java

private static String loadQuery(String filePath) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);
    return lines.stream().collect(Collectors.joining("\n"));
}

From source file:eu.freme.broker.integration_tests.EServiceTest.java

public static String readFile(String file) throws IOException {
    StringBuilder bldr = new StringBuilder();
    for (String line : Files.readAllLines(Paths.get(file), StandardCharsets.UTF_8)) {
        bldr.append(line).append('\n');
    }//from w  w w .j a va  2s .  c o  m
    return bldr.toString();
}

From source file:io.takari.maven.testing.executor.ForkedLauncher.java

@Override
public String getMavenVersion() throws IOException, LauncherException {
    // TODO cleanup, there is no need to write log file, for example

    File logFile;//from ww w  .  j a va  2s . c  o  m
    try {
        logFile = File.createTempFile("maven", "log");
    } catch (IOException e) {
        throw new LauncherException("Error creating temp file", e);
    }

    // disable EMMA runtime controller port allocation, should be harmless if EMMA is not used
    Map<String, String> envVars = Collections.singletonMap("MAVEN_OPTS", "-Demma.rt.control=false");
    run(new String[] { "--version" }, envVars, new File(""), new File(""), logFile);

    List<String> logLines = Files.readAllLines(logFile.toPath(), Charset.defaultCharset());
    // noinspection ResultOfMethodCallIgnored
    logFile.delete();

    String version = extractMavenVersion(logLines);

    if (version == null) {
        throw new LauncherException("Illegal Maven output: String 'Maven' not found in the following output:\n"
                + join(logLines, "\n"));
    } else {
        return version;
    }
}

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

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

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

            String[] argsParam = { "zookeeper", ".*", 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:org.duracloud.snapshot.service.impl.SpaceItemWriterTest.java

/**
 * @param string// w  w w . ja  v a 2 s  .c  o  m
 * @return
 * @throws IOException 
 */
private List<String> getLines(String filename) throws IOException {
    List<String> lines = Files.readAllLines(ContentDirUtils.getPath(contentDir, filename),
            StandardCharsets.UTF_8);
    Collections.sort(lines, new Comparator<String>() {
        /* (non-Javadoc)
         * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
         */
        @Override
        public int compare(String o1, String o2) {
            String path1 = getPath(o1);
            String path2 = getPath(o2);

            return path1.compareTo(path2);
        }

        private String getPath(String string) {
            int index = string.indexOf(" ");
            return string.substring(index + 1);
        }
    });
    return lines;
}

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

@Test
public void testNoExceptions() throws Exception {
    configure(Collections.emptyMap(), Collections.emptyMap(), false);
    final String msg = "Logging test: JsonFormatterTestCase.testNoExceptions";
    int statusCode = getResponse(msg,
            Collections.singletonMap(LoggingServiceActivator.LOG_EXCEPTION_KEY, "false"));
    Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);

    final List<String> expectedKeys = createDefaultKeys();

    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);
            validateStackTrace(json, false, false);
        }/*from   w ww  . j  a  v a2 s .  c om*/
    }
}

From source file:org.uma.jmetal.util.experiment.component.ComputeQualityIndicators.java

public void findBestIndicatorFronts(Experiment<?, Result> experiment) throws IOException {
    for (GenericIndicator<?> indicator : experiment.getIndicatorList()) {
        for (TaggedAlgorithm<Result> algorithm : experiment.getAlgorithmList()) {
            String algorithmDirectory;
            algorithmDirectory = experiment.getExperimentBaseDirectory() + "/data/" + algorithm.getTag();

            for (Problem<?> problem : experiment.getProblemList()) {
                String indicatorFileName = algorithmDirectory + "/" + problem.getName() + "/"
                        + indicator.getName();
                Path indicatorFile = Paths.get(indicatorFileName);
                if (indicatorFile == null) {
                    throw new JMetalException("Indicator file " + indicator.getName() + " doesn't exist");
                }/*from www.  j  a  va 2s.c  o  m*/

                List<String> fileArray;
                fileArray = Files.readAllLines(indicatorFile, StandardCharsets.UTF_8);

                List<Pair<Double, Integer>> list = new ArrayList<>();

                for (int i = 0; i < fileArray.size(); i++) {
                    Pair<Double, Integer> pair = new ImmutablePair<>(Double.parseDouble(fileArray.get(i)), i);
                    list.add(pair);
                }

                Collections.sort(list, new Comparator<Pair<Double, Integer>>() {
                    @Override
                    public int compare(Pair<Double, Integer> pair1, Pair<Double, Integer> pair2) {
                        if (Math.abs(pair1.getLeft()) > Math.abs(pair2.getLeft())) {
                            return 1;
                        } else if (Math.abs(pair1.getLeft()) < Math.abs(pair2.getLeft())) {
                            return -1;
                        } else {
                            return 0;
                        }
                    }
                });
                String bestFunFileName;
                String bestVarFileName;
                String medianFunFileName;
                String medianVarFileName;

                String outputDirectory = algorithmDirectory + "/" + problem.getName();

                bestFunFileName = outputDirectory + "/BEST_" + indicator.getName() + "_FUN.tsv";
                bestVarFileName = outputDirectory + "/BEST_" + indicator.getName() + "_VAR.tsv";
                medianFunFileName = outputDirectory + "/MEDIAN_" + indicator.getName() + "_FUN.tsv";
                medianVarFileName = outputDirectory + "/MEDIAN_" + indicator.getName() + "_VAR.tsv";
                if (indicator.isTheLowerTheIndicatorValueTheBetter()) {
                    String bestFunFile = outputDirectory + "/" + experiment.getOutputParetoFrontFileName()
                            + list.get(0).getRight() + ".tsv";
                    String bestVarFile = outputDirectory + "/" + experiment.getOutputParetoSetFileName()
                            + list.get(0).getRight() + ".tsv";

                    Files.copy(Paths.get(bestFunFile), Paths.get(bestFunFileName), REPLACE_EXISTING);
                    Files.copy(Paths.get(bestVarFile), Paths.get(bestVarFileName), REPLACE_EXISTING);
                } else {
                    String bestFunFile = outputDirectory + "/" + experiment.getOutputParetoFrontFileName()
                            + list.get(list.size() - 1).getRight() + ".tsv";
                    String bestVarFile = outputDirectory + "/" + experiment.getOutputParetoSetFileName()
                            + list.get(list.size() - 1).getRight() + ".tsv";

                    Files.copy(Paths.get(bestFunFile), Paths.get(bestFunFileName), REPLACE_EXISTING);
                    Files.copy(Paths.get(bestVarFile), Paths.get(bestVarFileName), REPLACE_EXISTING);
                }

                int medianIndex = list.size() / 2;
                String medianFunFile = outputDirectory + "/" + experiment.getOutputParetoFrontFileName()
                        + list.get(medianIndex).getRight() + ".tsv";
                String medianVarFile = outputDirectory + "/" + experiment.getOutputParetoSetFileName()
                        + list.get(medianIndex).getRight() + ".tsv";

                Files.copy(Paths.get(medianFunFile), Paths.get(medianFunFileName), REPLACE_EXISTING);
                Files.copy(Paths.get(medianVarFile), Paths.get(medianVarFileName), REPLACE_EXISTING);
            }
        }
    }
}