Example usage for java.nio.file Files lines

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

Introduction

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

Prototype

public static Stream<String> lines(Path path, Charset cs) throws IOException 

Source Link

Document

Read all lines from a file as a Stream .

Usage

From source file:downloadwebpages.DownloadWebpages.java

/**
 * read the webpages in the text file and save them in the java list
 *///  w w  w  .j av a2  s.com
private void getWebpagesFromFile() {
    try {
        System.out.println("Reading: " + webpagesTxtFilePath);
        webpages = new ArrayList<>(); // initialize list

        Stream<String> stream = Files.lines(Paths.get(webpagesTxtFilePath), Charset.defaultCharset());
        stream.forEach((line) -> {
            System.out.println("Read line: " + line);
            String[] split = line.split("\\t");
            if (split.length > 1) {
                webpages.add(new Pair(split[0], split[1]));
            }
        });
        //stream.forEach(System.out::println); // print line from file
    } catch (IOException ex) {
        Logger.getLogger(DownloadWebpages.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.security.KubernetesV2Credentials.java

public String lookupDefaultNamespace() {
    String namespace = defaultNamespace;
    try {//from   w  ww  . jav  a 2  s  . co m
        Optional<String> serviceAccountNamespace = Files
                .lines(serviceAccountNamespacePath, StandardCharsets.UTF_8).findFirst();
        namespace = serviceAccountNamespace.orElse("");
    } catch (IOException e) {
        try {
            namespace = jobExecutor.defaultNamespace(this);
        } catch (KubectlException ke) {
            log.debug("Failure looking up desired namespace, defaulting to {}", defaultNamespace, ke);
        }
    } catch (Exception e) {
        log.debug("Error encountered looking up default namespace, defaulting to {}", defaultNamespace, e);
    }
    if (StringUtils.isEmpty(namespace)) {
        namespace = defaultNamespace;
    }
    return namespace;
}

From source file:pe.chalk.takoyaki.Takoyaki.java

public synchronized Takoyaki init() throws IOException, JSONException, ReflectiveOperationException {
    if (this.getLogger() != null)
        return this;

    this.addTargetClasses(NaverCafe.class, NamuWiki.class);
    Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown));

    this.logger = new Logger();
    this.getLogger().addStream(new LoggerStream(TextFormat.Type.ANSI, System.out));
    this.getLogger().addStream(new LoggerStream(TextFormat.Type.NONE,
            new PrintStream(new FileOutputStream("Takoyaki.log", true), true, "UTF-8")));
    this.getLogger().info(" : " + Takoyaki.VERSION);

    try {/*from  ww  w. j  av a 2s  . co  m*/
        final Path propertiesPath = Paths.get("Takoyaki.json");
        if (!Files.exists(propertiesPath)) {
            this.getLogger().info("? ?: " + propertiesPath.toString());
            Files.write(propertiesPath, Takoyaki.DEFAULT_CONFIG, StandardCharsets.UTF_8);
        }

        this.getLogger().info("? : " + propertiesPath);
        final JSONObject properties = new JSONObject(
                Files.lines(propertiesPath, StandardCharsets.UTF_8).collect(Collectors.joining()));

        Utils.buildStream(JSONObject.class, properties.getJSONArray("targets")).map(Target::create)
                .forEach(this::addTarget);

        final Path pluginsPath = Paths.get("plugins");
        if (!Files.exists(pluginsPath))
            Files.createDirectories(pluginsPath);

        List<String> excludedPlugins = Utils
                .buildStream(String.class, properties.getJSONObject("options").getJSONArray("excludedPlugins"))
                .collect(Collectors.toList());
        new PluginLoader().load(Files.list(pluginsPath)
                .filter(PluginLoader.PLUGIN_FILTER.apply(excludedPlugins)).collect(Collectors.toList()))
                .forEach(this::addPlugin);
    } catch (Exception e) {
        this.getLogger().error(e.getClass().getName() + ": " + e.getMessage());
        throw e;
    }

    return this;
}

From source file:org.opennms.features.topology.plugins.topo.graphml.GraphMLEdgeStatusProvider.java

@Override
public Map<EdgeRef, Status> getStatusForEdges(EdgeProvider edgeProvider, Collection<EdgeRef> edges,
        Criteria[] criteria) {/* w  ww. jav  a  2  s  . c om*/
    final List<StatusScript> scripts = Lists.newArrayList();
    try (final DirectoryStream<Path> stream = Files.newDirectoryStream(getScriptPath())) {
        for (final Path path : stream) {
            final String extension = FilenameUtils.getExtension(path.toString());
            final ScriptEngine scriptEngine = this.scriptEngineManager.getEngineByExtension(extension);
            if (scriptEngine == null) {
                LOG.warn("No script engine found for extension '{}'", extension);
                continue;
            }
            LOG.debug("Found script: path={}, extension={}, engine={}", path, extension, scriptEngine);
            try (final Stream<String> lines = Files.lines(path, Charset.defaultCharset())) {
                final String source = lines.collect(Collectors.joining("\n"));
                scripts.add(new StatusScript(scriptEngine, source));
            }
        }
    } catch (final IOException e) {
        LOG.error("Failed to walk template directory: {}", getScriptPath());
        return Collections.emptyMap();
    }

    return serviceAccessor.getTransactionOperations()
            .execute(transactionStatus -> edges.stream().filter(eachEdge -> eachEdge instanceof GraphMLEdge)
                    .map(edge -> (GraphMLEdge) edge)
                    .map(edge -> new HashMap.SimpleEntry<>(edge, computeEdgeStatus(scripts, edge)))
                    .filter(e -> e.getValue() != null)
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
}

From source file:org.codice.ddf.admin.insecure.defaults.service.DefaultUsersDeletionScheduler.java

public Instant installationDate() {
    if (!getTempTimestampFilePath().toFile().exists()) {
        return null;
    }/*www  .  j  av a2  s.c  om*/

    try (Stream<String> lines = Files.lines(getTempTimestampFilePath(), StandardCharsets.UTF_8)) {
        return lines.filter(StringUtils::isNotBlank).map(Instant::parse).findFirst().orElse(null);

    } catch (IOException e) {
        LOGGER.debug("Unable to read installation date.", e);
        return null;
    }
}

From source file:org.codice.ddf.admin.insecure.defaults.service.DefaultUsersDeletionScheduler.java

public boolean defaultUsersExist() {
    try (Stream<String> defaultUsers = Files.lines(getUsersPropertiesFilePath(), StandardCharsets.UTF_8)) {
        return defaultUsers.filter(StringUtils::isNotBlank).filter(line -> !line.startsWith("#"))
                .anyMatch(line -> true);
    } catch (IOException e) {
        LOGGER.debug("Unable to access users.properties file.", e);
        return true;
    }/*from  w  w w.  jav a 2 s. c om*/
}

From source file:org.opendatakit.briefcase.reused.UncheckedFiles.java

public static Stream<String> lines(Path path) {
    try {// w  w  w .j a va2  s. c om
        return Files.lines(path, UTF_8);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:de.andreasschoknecht.LS3.DocumentCollection.java

/**
 * Load Term-Document Matrix data stored in a text file.
 *
 * @param filePath The file path to the file containing the Term-Document Matrix data.
 *//*from   w  w w.j  a  va2  s .  co m*/
public void loadTDMatrix(String filePath) {

    try (Stream<String> lines = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) {
        ArrayList<String> files = new ArrayList<String>();
        TDMatrix tdMatrix;
        int rowNumber = 0;
        int columnNumber = 0;

        Iterator<String> itr = lines.iterator();
        while (itr.hasNext()) {
            String line = itr.next();

            switch (line) {
            case "--------------------COLLECTION--------------------":
                System.out.println(line);
                String line2 = itr.next();
                while (!line2.equals("----------------------------------------")) {
                    files.add(line2);
                    line2 = itr.next();
                }
                break;
            case "--------------------TERM LIST--------------------":
                System.out.println(line);
                termCollection.clear();
                line2 = itr.next();
                while (!line2.equals("----------------------------------------")) {
                    termCollection.add(line2);
                    line2 = itr.next();
                }
                break;
            case "--------------------ROW NUMBER--------------------":
                System.out.println(line);
                rowNumber = Integer.parseInt(itr.next());
                break;
            case "--------------------COLUMN NUMBER--------------------":
                System.out.println(line);
                columnNumber = Integer.parseInt(itr.next());
                break;
            case "--------------------MATRIX DATA--------------------":
                System.out.println(line);
                tdMatrix = new TDMatrix(rowNumber, columnNumber);
                tdMatrix.setRowNumber(rowNumber);
                tdMatrix.setColumnNumber(columnNumber);
                tdMatrix.setTermArray(termCollection.toArray(new String[0]));

                int rowCounter = 0;
                while (itr.hasNext()) {
                    line2 = itr.next();
                    String[] tokens = line2.split(" ");
                    double[] values = new double[tokens.length];
                    for (int i = 0; i < tokens.length; i++)
                        values[i] = Double.parseDouble(tokens[i]);

                    tdMatrix.fillRow(values, rowCounter);

                    rowCounter++;
                }

                this.tdMatrix = tdMatrix;
                break;
            }

        }

        setFileList(files.toArray(new String[0]));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("File loaded");
}

From source file:com.themodernway.server.core.io.IO.java

public static final Stream<String> lines(final Path path, final boolean greedy) throws IOException {
    final Stream<String> lines = Files.lines(CommonOps.requireNonNull(path), UTF_8_CHARSET);

    if (greedy) {
        return CommonOps.toList(lines).stream();
    }//from ww  w . ja va2 s.  c  om
    return lines;
}

From source file:com.saptarshidebnath.lib.processrunner.process.RunnerFactoryTest.java

@Test
public void getProcessMoreDetailed()
        throws IOException, InterruptedException, ProcessConfigurationException, ExecutionException {
    Configuration configuration = new ConfigBuilder(getDefaultInterpreter(), getInterPreterVersion())
            .setWorkigDir(ProcessRunnerConstants.DEFAULT_CURRENT_DIR_PATH)
            .setMasterLogFile(File.createTempFile(ProcessRunnerConstants.FILE_PREFIX_NAME_LOG_DUMP,
                    ProcessRunnerConstants.FILE_SUFFIX_JSON), false)
            .build();//www . j a  v a  2s  . c  o m
    final Runner runner = RunnerFactory.getRunner(configuration);
    final Output response = runner.run();
    assertThat("Validating process return code : ", response.getReturnCode(), is(0));
    final File masterLog = response.getMasterLogAsJson();
    assertThat("Validating if JSON log dump is created : ", masterLog.exists(), is(true));

    List<OutputRecord> outPutRecordList = Files
            .lines(Paths.get(configuration.getMasterLogFile().getCanonicalPath()), configuration.getCharset())
            .map(line -> GSON.fromJson(line, OutputRecord.class)).collect(Collectors.toList());
    assertThat("Validating json log record number : ", outPutRecordList.size(), is(getVersionPutputSize()));
    assertThat("Validating json log content : ", outPutRecordList.get(this.arryPosition).getOutputText(),
            startsWith(getInitialVersionComments()));
    assertThat("Checking if master file gets deleted or not", masterLog.delete(), is(true));
}