Example usage for java.io BufferedReader lines

List of usage examples for java.io BufferedReader lines

Introduction

In this page you can find the example usage for java.io BufferedReader lines.

Prototype

public Stream<String> lines() 

Source Link

Document

Returns a Stream , the elements of which are lines read from this BufferedReader .

Usage

From source file:edu.umd.umiacs.clip.tools.io.AllFiles.java

private static Stream<String> overridenLines(Path path) throws IOException {
    BufferedReader br = null;
    try {// w  w w .j ava2 s  .  c  om
        br = new BufferedReader(
                new InputStreamReader(new BufferedInputStream(newInputStream(path), BUFFER_SIZE),
                        UTF_8.newDecoder().onMalformedInput(IGNORE)));
        return br.lines().onClose(asUncheckedRunnable(br));
    } catch (IOException e) {
        try {
            br.close();
        } catch (Exception ex) {
            try {
                e.addSuppressed(ex);
            } catch (Throwable ignore) {
            }
        }
        throw e;
    }
}

From source file:com.spotify.heroic.shell.Tasks.java

public static <T> Stream<T> parseJsonLines(final ObjectMapper mapper, final Optional<Path> file,
        final ShellIO io, final Class<T> type) {
    return file.<Stream<T>>map(f -> {
        try {//  w  w w .  j  a v a2  s.  c o m
            final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(io.newInputStream(f), Charsets.UTF_8));

            return reader.lines().onClose(() -> {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException("Failed to close file", e);
                }
            }).map(line -> {
                try {
                    return mapper.readValue(line.trim(), type);
                } catch (IOException e) {
                    throw new RuntimeException("Failed to decode line (" + line.trim() + ")", e);
                }
            });
        } catch (final IOException e) {
            throw new RuntimeException("Failed to open file: " + f, e);
        }
    }).orElseGet(Stream::empty);
}

From source file:ca.polymtl.dorsal.libdelorean.statedump.Statedump.java

/**
 * Retrieve a previously-saved statedump.
 *
 * @param parentPath//from w  w  w. j ava  2 s  . c om
 *            The expected location of the statedump file. Like the
 *            corresponding parameter in {@link #dumpState}, this is the
 *            parent path of the TC-specific subdirectory.
 * @param ssid
 *            The ID of the state system to retrieve
 * @return The corresponding de-serialized statedump. Returns null if there
 *         are no statedump for this state system ID (or no statedump
 *         directory at all).
 */
public static @Nullable Statedump loadState(Path parentPath, String ssid) {
    /* Find the state dump directory */
    Path sdPath = parentPath.resolve(STATEDUMP_DIRECTORY);
    if (!Files.isDirectory(sdPath)) {
        return null;
    }

    /* Find the state dump file */
    String fileName = ssid + FILE_SUFFIX;
    Path filePath = sdPath.resolve(fileName);
    if (!Files.exists(filePath)) {
        return null;
    }

    try (InputStreamReader in = new InputStreamReader(
            Files.newInputStream(filePath, StandardOpenOption.READ))) {
        BufferedReader bufReader = new BufferedReader(in);
        String json = bufReader.lines().collect(Collectors.joining("\n")); //$NON-NLS-1$
        JSONObject root = new JSONObject(json);

        return Serialization.stateDumpFromJsonObject(root, ssid);
    } catch (IOException | JSONException e) {
        return null;
    }
}

From source file:org.dkpro.core.api.embeddings.text.TextFormatVectorizerUtils.java

/**
 * Read embeddings in text format from an InputStream.
 * Each line is expected to have a whitespace-separated list {@code <token> <value1> <value2> ...}.
 *
 * @param inputStream an {@link InputStream}
 * @param hasHeader   if true, read size and dimensionality from the first line
 * @return a {@code Map<String, float[]>} mapping each token to a vector.
 * @throws IOException if the input file cannot be read
 *//*from   w w w .  j a  va2  s.  co  m*/
public static Map<String, float[]> readEmbeddingFileTxt(InputStream inputStream, boolean hasHeader)
        throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    final int dimensions;
    final int size;

    if (hasHeader) {
        String[] header = reader.readLine().split(" ");
        assert header.length == 2;
        size = Integer.parseInt(header[0]);
        dimensions = Integer.parseInt(header[1]);
    } else {
        dimensions = -1;
        size = -1;
    }

    Map<String, float[]> embeddings = reader.lines().map(TextFormatVectorizerUtils::lineToEmbedding)
            .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    reader.close();

    /* assert size and dimension */
    if (hasHeader) {
        /* check that size read matches header information */
        LOG.debug("Checking number and vector sizes for all embeddings.");
        assert size == embeddings.size();
        assert embeddings.values().stream().allMatch(vector -> dimensions == vector.length);
    } else {
        LOG.debug("Checking vector sizes for all embeddings.");
        int firstLength = embeddings.values().stream().findAny().get().length;
        assert embeddings.values().stream().allMatch(vector -> firstLength == vector.length);
    }

    return embeddings;
}

From source file:com.neu.controller.OutcomeController.java

@RequestMapping(value = "/outcome.htm", method = RequestMethod.GET, headers = "Accept=*/*", produces = "application/json")
@ResponseStatus(HttpStatus.OK)//from   ww w. ja v a2  s  .c o m
public @ResponseBody String searchresult(HttpServletRequest request) throws Exception {
    System.out.println("in drugsearch controller");
    String action = request.getParameter("action");
    List<DrugOutcome> outcomes;
    String csvFile = "Merge.csv";
    String rpath = request.getRealPath("/");
    rpath = rpath + "/dataFiles/" + csvFile;
    Pattern pattern = Pattern.compile(",");

    BufferedReader in = new BufferedReader(new FileReader(rpath));
    outcomes = in.lines().skip(1).map(line -> {
        String[] x = pattern.split(line);
        return new DrugOutcome(x[3], x[20], x[7], x[6], x[8], x[13], x[4], x[5]);
    }).collect(Collectors.toList());
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
    mapper.writeValue(System.out, outcomes);

    //            Drugs drug=new Drugs("AZ","sn");
    return mapper.writeValueAsString(outcomes);
}

From source file:com.neu.controller.SearchController.java

@RequestMapping(value = "/search.htm", method = RequestMethod.GET, headers = "Accept=*/*", produces = "application/json")
@ResponseStatus(HttpStatus.OK)//from   w w  w .j  a  va  2  s . co m
public @ResponseBody String searchresult(HttpServletRequest request) throws Exception {
    System.out.println("in drugsearch controller");
    String action = request.getParameter("action");
    List<Drugs> drugs;
    String csvFile = "UserSearch.csv";
    String rpath = request.getRealPath("/");
    rpath = rpath + "/dataFiles/" + csvFile;

    Pattern pattern = Pattern.compile(",");

    BufferedReader in = new BufferedReader(new FileReader(rpath));
    drugs = in.lines().skip(1).map(line -> {
        String[] x = pattern.split(line);
        return new Drugs(x[0], x[3]);
    }).collect(Collectors.toList());
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
    mapper.writeValue(System.out, drugs);

    //            Drugs drug=new Drugs("AZ","sn");
    return mapper.writeValueAsString(drugs);
}

From source file:com.joconner.g11n.charprop.service.BlocksService.java

public BlocksService() {
    noBlock = new Block("No_Block", -1, -1);
    blocks = new ArrayList<>();
    InputStream blockInputStream = ClassLoader.getSystemResourceAsStream("unicode/Blocks.txt");
    InputStreamReader blockReader = new InputStreamReader(blockInputStream, Charset.forName("UTF-8"));
    BufferedReader reader = new BufferedReader(blockReader);
    reader.lines().filter(s -> s.matches("^\\p{XDigit}{4,6}\\.\\.\\p{XDigit}{4,6};\\s.+"))
            .forEach((String t) -> {
                int rangeIdx = t.indexOf("..");
                int rangeEndIdx = t.indexOf(";");
                int nameIdx = t.indexOf(" ", rangeIdx) + 1;
                int blockStart = Integer.parseInt(t.substring(0, rangeIdx), 16);
                int blockEnd = Integer.parseInt(t.substring(rangeIdx + 2, rangeEndIdx), 16);
                Block b = new Block(t.substring(nameIdx), blockStart, blockEnd);
                blocks.add(b);/*from w  w w  . j  a v  a2  s. co  m*/
            });
    try {
        reader.close();
    } catch (IOException ex) {

    }

}

From source file:org.apache.james.spamassassin.mock.MockSpamd.java

private boolean isSpam(BufferedReader in) throws IOException {
    try {/*from   w  w w.j  a v  a  2 s. c  om*/
        return in.lines().anyMatch(line -> line.contains(GTUBE));
    } finally {
        consume(in);
    }
}

From source file:uk.ac.kcl.iop.brc.core.pipeline.dncpipeline.service.PythonService.java

/**
 * Runs the Python interpreter.//  www  .j a v  a2 s.c o m
 * @param args List of arguments to be supplied to the python command.
 * @return Result from python string
 * @throws IOException
 */
public String runFile(List<String> args) throws IOException {
    LinkedList<String> list = new LinkedList<>(args);
    list.addFirst("python");
    ProcessBuilder processBuilder = new ProcessBuilder(list);
    Process p = processBuilder.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    StringWriter stringWriter = new StringWriter();
    in.lines().forEach(stringWriter::append);
    p.destroy();
    return stringWriter.toString();
}

From source file:de.tudarmstadt.lt.lm.app.FilterLines.java

void runParallel(Reader r) {
    BufferedReader br = new BufferedReader(r);
    br.lines().parallel().forEach(line -> processLine(line));
}