Example usage for java.nio.file Files newBufferedReader

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

Introduction

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

Prototype

public static BufferedReader newBufferedReader(Path path) throws IOException 

Source Link

Document

Opens a file for reading, returning a BufferedReader to read text from the file in an efficient manner.

Usage

From source file:vn.edu.vnu.uet.nlp.smt.ibm.IBMModel3.java

public IBMModel3(String model) {
    super(model);

    if (!model.endsWith("/")) {
        model = model + "/";
    }/*from  w w w  . j av a  2 s .c  o  m*/

    String dFileName = model + IConstants.distortionModelName;
    String nFileName = model + IConstants.fertilityModelName;
    String nullInsertionFileName = model + IConstants.nullInsertionModelName;

    try {
        d = Utils.loadArray(dFileName);
        n = Utils.loadObject(nFileName);
        BufferedReader br = Files.newBufferedReader(Paths.get(nullInsertionFileName));
        String line = br.readLine();
        if (line == null || !line.startsWith("p0 = ")) {
            System.err.println("Error in null insertion file!");
            return;
        }
        p0 = Double.parseDouble(line.substring("p0 = ".length()));
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.asterix.external.util.FeedLogManager.java

public synchronized void open() throws IOException {
    // read content of logs.
    BufferedReader reader = Files.newBufferedReader(
            Paths.get(dir.toAbsolutePath().toString() + File.separator + PROGRESS_LOG_FILE_NAME));
    String log = reader.readLine();
    while (log != null) {
        if (log.startsWith(END_PREFIX)) {
            completed.add(getSplitId(log));
        }//  ww  w .j  a  v a2s  .  co m
        log = reader.readLine();
    }
    reader.close();

    progressLogger = Files.newBufferedWriter(
            Paths.get(dir.toAbsolutePath().toString() + File.separator + PROGRESS_LOG_FILE_NAME),
            StandardCharsets.UTF_8, StandardOpenOption.APPEND);
    errorLogger = Files.newBufferedWriter(
            Paths.get(dir.toAbsolutePath().toString() + File.separator + ERROR_LOG_FILE_NAME),
            StandardCharsets.UTF_8, StandardOpenOption.APPEND);
    recordLogger = Files.newBufferedWriter(
            Paths.get(dir.toAbsolutePath().toString() + File.separator + BAD_RECORDS_FILE_NAME),
            StandardCharsets.UTF_8, StandardOpenOption.APPEND);
}

From source file:org.thingsboard.server.service.install.cql.CassandraDbHelper.java

public static void loadCf(KeyspaceMetadata ks, Session session, String cfName, String[] columns,
        Path sourceFile, boolean parseHeader) throws Exception {
    TableMetadata tableMetadata = ks.getTable(cfName);
    PreparedStatement prepared = session.prepare(createInsertStatement(cfName, columns));
    CSVFormat csvFormat = CSV_DUMP_FORMAT;
    if (parseHeader) {
        csvFormat = csvFormat.withFirstRecordAsHeader();
    } else {//from  w w  w  .ja  va 2s  .co  m
        csvFormat = CSV_DUMP_FORMAT.withHeader(columns);
    }
    try (CSVParser csvParser = new CSVParser(Files.newBufferedReader(sourceFile), csvFormat)) {
        csvParser.forEach(record -> {
            BoundStatement boundStatement = prepared.bind();
            for (String column : columns) {
                setColumnValue(tableMetadata, column, record, boundStatement);
            }
            session.execute(boundStatement);
        });
    }
}

From source file:org.mortbay.jetty.load.generator.starter.LoadGeneratorStarterTest.java

@Test
public void json_serial_deserial_from_groovy() throws Exception {
    try (Reader reader = Files
            .newBufferedReader(Paths.get("src/test/resources/loadgenerator_profile.groovy"))) {
        Resource resource = (Resource) AbstractLoadGeneratorStarter.evaluateScript(reader);
        String path = AbstractLoadGeneratorStarter.writeAsJsonTmp(resource);
        Resource fromJson = AbstractLoadGeneratorStarter.evaluateJson(Paths.get(path));
        Assert.assertEquals(resource.descendantCount(), fromJson.descendantCount());
    }// w  w w  .jav a 2s .com
}

From source file:de.decoit.simu.cbor.xml.dictionary.parser.DictionaryParser.java

/**
 * Parse the dictionary description located in the specified input file.
 *
 * @param inFile Input file containing the description
 * @return The filled dictionary/*from  w ww.ja  v a 2 s  .  co m*/
 * @throws IOException if the input file cannot be read or contains illegal or corrupt lines
 */
public Dictionary parseDictionary(Path inFile) throws IOException {
    if (inFile == null) {
        throw new IllegalArgumentException("Input file must not be null");
    }

    this.br = Files.newBufferedReader(inFile);

    // Read next line from buffer
    String srcLine = readLineFromBuffer();
    while (srcLine != null) {
        // Create a RegEx matcher for this line
        Matcher m = p.matcher(srcLine);

        DictionaryNamespace dns = parseDictionaryNamespace(m);
        this.dictInstance.addNamespace(dns);

        // Read next line from buffer
        srcLine = readLineFromBuffer();
    }

    this.br.close();
    this.br = null;

    return dictInstance;
}

From source file:javalibs.CSVExtractor.java

private void readCSV() {
    try {/*from  w w  w.j  a  v a2  s  .c  o  m*/
        CSVParser parser = new CSVParser(Files.newBufferedReader(Paths.get(this.inCSV)),
                CSVFormat.DEFAULT.withHeader().withIgnoreHeaderCase().withTrim());

        // Get all headers
        Map<String, Integer> rawHeaders = parser.getHeaderMap();

        // Store the inRecords
        this.inRecords = parser.getRecords();
        parser.close();

        orderHeaders(rawHeaders);
    } catch (IOException e) {
        log_.die(e);
    }
}

From source file:keywhiz.cli.ClientUtils.java

/**
 * Load cookies from the specified file from JSON to a name to value mapping.
 *
 * @param path Location of serialized cookies to load.
 * @return list of cookies that were read {@link JsonCookie}.
 * @throws IOException// w  w w  . ja v a  2s  .  c  o  m
 */
public static List<HttpCookie> loadCookies(Path path) throws IOException {
    List<HttpCookie> cookieList;
    try (BufferedReader reader = Files.newBufferedReader(path)) {
        List<JsonCookie> jsonCookies = Jackson.newObjectMapper().readValue(reader,
                new TypeReference<List<JsonCookie>>() {
                });
        cookieList = jsonCookies.stream().map(c -> JsonCookie.toHttpCookie(c)).collect(Collectors.toList());
    }
    return cookieList;
}

From source file:org.dbflute.intro.app.logic.dfprop.DfpropUpdateLogic.java

private String replaceDfpropFileContent(File file, Function<String, String> lineReplacer) {
    try (BufferedReader br = Files.newBufferedReader(file.toPath())) {
        boolean endComment = false;
        final StringBuilder sb = new StringBuilder();
        while (true) {
            String line = br.readLine();
            if (line == null) {
                break;
            }//  ww w.  ja v  a  2s . com
            if (StringUtils.equals(line, "map:{")) {
                endComment = true;
            }
            if (endComment) {
                line = lineReplacer.apply(line);
            }
            sb.append(line).append("\n");
        }
        return sb.toString();
    } catch (IOException e) {
        throw new LaSystemException("Cannot replace dfprop", e);
    }
}

From source file:org.esa.snap.smart.configurator.VMParameters.java

private static Properties loadSnapConfProperties() {

    Properties properties = new Properties();
    try {/*  w  ww. j  a v a 2  s.  c om*/
        try (BufferedReader reader = Files.newBufferedReader(getSnapConfigPath())) {
            properties.load(reader);
        }
    } catch (IOException e) {
        // we could not find the snap config file. We log an error and continue, it will be created
        SystemUtils.LOG
                .severe(String.format("Can't load snap config file '%s'", getSnapConfigPath().toString()));
    }

    return properties;
}