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) throws IOException 

Source Link

Document

Read all lines from a file.

Usage

From source file:com.ethercamp.harmony.keystore.FileSystemKeystore.java

/**
 * @return some loaded key or null//from  www  . j a  v a  2s  .c  om
 */
@Override
public ECKey loadStoredKey(String address, String password) throws RuntimeException {
    return getFiles().stream().filter(f -> hasAddressInName(address, f)).map(f -> {
        try {
            return Files.readAllLines(f.toPath()).stream().collect(Collectors.joining(""));
        } catch (IOException e) {
            throw new RuntimeException("Problem reading keystore file for address:" + address);
        }
    }).map(content -> keystoreFormat.fromKeystore(content, password)).findFirst().orElse(null);
}

From source file:edu.vassar.cs.cmpu331.tvi.Main.java

private void run(String filename) {
    if (memory > 0) {
        cpu = new CPU(memory);
    } else {//from   w  ww  . ja  va2s.  co m
        cpu = new CPU();
    }
    if (tracing) {
        System.out.println("Tracing enabled.");
        cpu.enableTracing();
    }
    if (debugging) {
        System.out.println("Debug output enabled.");
        cpu.enableDebug();
    }

    Path file = Paths.get(filename);
    if (Files.notExists(file)) {
        System.out.println("ERROR: File not found: " + filename);
        return;
    }

    System.out.println("Running " + filename);
    try {
        if (debugging) {
            System.out.println("Loading opcodes.");
        }
        List<String> lines = Files.readAllLines(file);
        for (String line : lines) {
            if (include(line)) {
                cpu.add(new Instruction(line));
            }
        }
        if (debugging) {
            System.out.println("Execution starting.");
        }
        cpu.run();
    } catch (IOException | TVIError e) {
        System.out.println(e.getMessage());
    }
}

From source file:org.springframework.cloud.stream.app.plugin.utils.SpringCloudStreamPluginUtils.java

public static void addAutoConfigImport(String generatedAppHome, String autoConfigClazz) throws IOException {
    Collection<File> files = FileUtils.listFiles(new File(generatedAppHome, "src/main/java"), null, true);
    Optional<File> first = files.stream().filter(f -> f.getName().endsWith("Application.java")).findFirst();

    if (first.isPresent()) {
        StringBuilder sb = new StringBuilder();
        File f1 = first.get();/*from   w  ww  .  ja v a  2s. co  m*/
        Files.readAllLines(f1.toPath()).forEach(l -> {
            if (l.startsWith("import org.springframework.boot.autoconfigure.SpringBootApplication;")) {
                sb.append(l).append("\n").append("import org.springframework.context.annotation.Import;\n");
            } else if (l.startsWith("@SpringBootApplication")) {
                sb.append(l).append("\n").append("@Import(").append(autoConfigClazz).append(")");
            } else {
                sb.append(l);
            }
            sb.append("\n");
        });
        Files.write(f1.toPath(), sb.toString().getBytes());
    }

}

From source file:com.cloudbees.jenkins.support.api.FileContent.java

@Override
public void writeTo(OutputStream os, ContentFilter filter) throws IOException {
    if (isBinary || filter == null) {
        writeTo(os);//w  w w  .  j a v  a2s  . c  o m
    }

    try {
        if (maxSize == -1) {
            for (String s : Files.readAllLines(file.toPath())) {
                String filtered = filter.filter(s);
                IOUtils.write(filtered, os);
            }
        } else {
            try (TruncatedFileReader reader = new TruncatedFileReader(file, maxSize)) {
                String s;
                while ((s = reader.readLine()) != null) {
                    String filtered = filter.filter(s);
                    IOUtils.write(filtered, os);
                }
            }
        }
    } catch (FileNotFoundException | NoSuchFileException e) {
        OutputStreamWriter osw = new OutputStreamWriter(os, ENCODING);
        try {
            PrintWriter pw = new PrintWriter(osw, true);
            try {
                pw.println("--- WARNING: Could not attach " + file + " as it cannot currently be found ---");
                pw.println();
                SupportLogFormatter.printStackTrace(e, pw);
            } finally {
                pw.flush();
            }
        } finally {
            osw.flush();
        }
    }
}

From source file:org.kitodo.production.exporter.download.ExportMetsIT.java

@Test
public void exportMetsTest() throws Exception {
    if (SystemUtils.IS_OS_WINDOWS) {
        // This is a workaround for the problem that the startExport method
        // is calling
        // an external shell script for creating directories. This code only
        // does the work of that script.
        // TODO Find a better way for changing script selection
        // corresponding to OS
        fileService.createDirectory(ConfigCore.getUriParameter(ParameterCore.DIR_USERS), userDirectory);
    }//from   w ww . ja va 2s . c om

    exportMets.startExport(process, exportUri);
    List<String> strings = Files.readAllLines(Paths.get(ConfigCore.getParameter(ParameterCore.DIR_USERS)
            + userDirectory + "/" + Helper.getNormalizedTitle(process.getTitle()) + "_mets.xml"));
    Assert.assertTrue("Export of metadata 'singleDigCollection' was wrong", strings.toString()
            .contains("<ns3:metadata name=\"singleDigCollection\">test collection</ns3:metadata>"));
    Assert.assertTrue("Export of metadata 'TitleDocMain' was wrong",
            strings.toString().contains("<ns3:metadata name=\"TitleDocMain\">test title</ns3:metadata>"));
    Assert.assertTrue("Export of metadata 'PublisherName' was wrong", strings.toString()
            .contains("<ns3:metadata name=\"PublisherName\">Publisher test name</ns3:metadata>"));

}

From source file:dyco4j.instrumentation.internals.CLI.java

private static void extendClassPath(final CommandLine cmdLine) throws IOException {
    try {//w  w  w .j  av a  2s  .  c om
        final URLClassLoader _urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        final Class<URLClassLoader> _urlClass = URLClassLoader.class;
        final Method _method = _urlClass.getDeclaredMethod("addURL", URL.class);
        _method.setAccessible(true);
        addEntryToClassPath(_urlClassLoader, _method, cmdLine.getOptionValue(IN_FOLDER_OPTION));
        final String _classpathConfig = cmdLine.getOptionValue(CLASSPATH_CONFIG_OPTION);
        if (_classpathConfig != null) {
            for (final String _s : Files.readAllLines(Paths.get(_classpathConfig))) {
                addEntryToClassPath(_urlClassLoader, _method, _s);
            }
        }
    } catch (final NoSuchMethodException _e) {
        throw new RuntimeException(_e);
    }
}

From source file:org.goobi.export.ExportMetsIT.java

@Test
public void exportMetsTest() throws Exception {
    if (SystemUtils.IS_OS_WINDOWS) {
        // This is a workaround for the problem that the startExport method
        // is calling
        // an external shell script for creating directories. This code only
        // does the work of that script.
        // TODO Find a better way for changing script selection
        // corresponding to OS
        fileService.createDirectory(Config.getUri(Parameters.DIR_USERS), userDirectory);
    }// ww w  . j a v  a 2  s  .  c o m

    exportMets.startExport(process, exportUri);
    List<String> strings = Files
            .readAllLines(Paths.get(Config.getParameter(Parameters.DIR_USERS) + userDirectory + "/"
                    + serviceManager.getProcessService().getNormalizedTitle(process.getTitle()) + "_mets.xml"));

    Assert.assertTrue("Export of metadata was wrong",
            strings.get(1).contains("<mods:publisher>Test Publisher</mods:publisher>"));
    Assert.assertTrue("Export of person was wrong",
            strings.get(1).contains("<mods:title>Test Title</mods:title>"));
    Assert.assertTrue("Export of metadata group was wrong",
            strings.get(1).contains("<mods:namePart type=\"given\">FirstTestName</mods:namePart>"));

}

From source file:org.elasticsearch.discovery.ec2.AmazonEC2Fixture.java

/**
 * Generates a XML response that describe the EC2 instances
 *///from w w w . j  a  v  a  2 s  .  com
private byte[] generateDescribeInstancesResponse() {
    final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
    xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    final StringWriter out = new StringWriter();
    XMLStreamWriter sw;
    try {
        sw = xmlOutputFactory.createXMLStreamWriter(out);
        sw.writeStartDocument();

        String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
        sw.setDefaultNamespace(namespace);
        sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
        {
            sw.writeStartElement("requestId");
            sw.writeCharacters(UUID.randomUUID().toString());
            sw.writeEndElement();

            sw.writeStartElement("reservationSet");
            {
                if (Files.exists(nodes)) {
                    for (String address : Files.readAllLines(nodes)) {

                        sw.writeStartElement("item");
                        {
                            sw.writeStartElement("reservationId");
                            sw.writeCharacters(UUID.randomUUID().toString());
                            sw.writeEndElement();

                            sw.writeStartElement("instancesSet");
                            {
                                sw.writeStartElement("item");
                                {
                                    sw.writeStartElement("instanceId");
                                    sw.writeCharacters(UUID.randomUUID().toString());
                                    sw.writeEndElement();

                                    sw.writeStartElement("imageId");
                                    sw.writeCharacters(UUID.randomUUID().toString());
                                    sw.writeEndElement();

                                    sw.writeStartElement("instanceState");
                                    {
                                        sw.writeStartElement("code");
                                        sw.writeCharacters("16");
                                        sw.writeEndElement();

                                        sw.writeStartElement("name");
                                        sw.writeCharacters("running");
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();

                                    sw.writeStartElement("privateDnsName");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("dnsName");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("instanceType");
                                    sw.writeCharacters("m1.medium");
                                    sw.writeEndElement();

                                    sw.writeStartElement("placement");
                                    {
                                        sw.writeStartElement("availabilityZone");
                                        sw.writeCharacters("use-east-1e");
                                        sw.writeEndElement();

                                        sw.writeEmptyElement("groupName");

                                        sw.writeStartElement("tenancy");
                                        sw.writeCharacters("default");
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();

                                    sw.writeStartElement("privateIpAddress");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();

                                    sw.writeStartElement("ipAddress");
                                    sw.writeCharacters(address);
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                        sw.writeEndElement();
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return out.toString().getBytes(UTF_8);
}

From source file:jp.toastkid.script.Controller.java

/**
 * Load script from file./*w w  w  .  j a va  2s.c om*/
 * @param file
 */
private void loadScript(final File file) {
    if (file == null || !file.exists()) {
        return;
    }
    try {
        scriptName.setText(file.getCanonicalPath());
        scripterInput.replaceText(
                Files.readAllLines(file.toPath()).stream().collect(Collectors.joining(System.lineSeparator())));
    } catch (final IOException e) {
        LOGGER.error("Caught error.", e);
    }
}

From source file:org.evosuite.junit.CoverageAnalysisWithRefectionSystemTest.java

@Test
public void testGetAllInterfaces() throws IOException {

    EvoSuite evosuite = new EvoSuite();

    String targetClass = ClassWithPrivateInterfaces.class.getCanonicalName();
    String testClass = ClassWithPrivateInterfacesTest.class.getCanonicalName();
    Properties.TARGET_CLASS = targetClass;

    Properties.CRITERION = new Properties.Criterion[] { Properties.Criterion.LINE };

    Properties.OUTPUT_VARIABLES = RuntimeVariable.Total_Goals + "," + RuntimeVariable.LineCoverage;
    Properties.STATISTICS_BACKEND = StatisticsBackend.CSV;
    Properties.COVERAGE_MATRIX = true;

    String[] command = new String[] { "-class", targetClass, "-Djunit=" + testClass, "-measureCoverage" };

    Object statistics = evosuite.parseCommandLine(command);
    Assert.assertNotNull(statistics);//from  www .j  a va2s  .c  o m

    // Assert coverage

    String statistics_file = System.getProperty("user.dir") + File.separator + Properties.REPORT_DIR
            + File.separator + "statistics.csv";
    System.out.println("statistics_file: " + statistics_file);

    CSVReader reader = new CSVReader(new FileReader(statistics_file));
    List<String[]> rows = reader.readAll();
    assertTrue(rows.size() == 2);
    reader.close();

    assertEquals("14", CsvJUnitData.getValue(rows, RuntimeVariable.Total_Goals.name()));
    assertEquals(0.93, Double.valueOf(CsvJUnitData.getValue(rows, RuntimeVariable.LineCoverage.name())), 0.01);

    // Assert that all test cases have passed

    String matrix_file = System.getProperty("user.dir") + File.separator + Properties.REPORT_DIR
            + File.separator + "data" + File.separator + targetClass + File.separator
            + Properties.Criterion.LINE.name() + File.separator + Properties.COVERAGE_MATRIX_FILENAME;
    System.out.println("matrix_file: " + matrix_file);

    List<String> lines = Files.readAllLines(FileSystems.getDefault().getPath(matrix_file));
    assertTrue(lines.size() == 1);

    assertEquals(13 + 1 + 1, lines.get(0).replace(" ", "").length()); // number of goals + test result ('+' pass, '-' fail)
    assertTrue(lines.get(0).replace(" ", "").endsWith("+"));
}