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, Charset cs) throws IOException 

Source Link

Document

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

Usage

From source file:com.talkdesk.geo.GeoCodeRepositoryBuilder.java

/**
 * Populate country data for the table ISO and lang / lat mapping
 *
 * @throws GeoResolverException/*from www .  ja  v  a 2  s.  c  o  m*/
 */
public void populateCountryData() throws GeoResolverException {
    try {
        if (connection == null)
            connection = connectToDatabase();

        if (!new File(countryDataLocation).exists()) {
            log.error("No Data file found for countryData. please add to data/country.csv ");
            return;
        }

        Path file = FileSystems.getDefault().getPath(countryDataLocation);
        Charset charset = Charset.forName("UTF-8");
        BufferedReader inputStream = Files.newBufferedReader(file, charset);
        String buffer;
        PreparedStatement preparedStatement;
        preparedStatement = connection.prepareStatement(
                "INSERT INTO countrycodes (COUNTRY_CODE , LATITUDE, LONGITUDE, NAME)" + " VALUES (?,?,?,?)");
        while ((buffer = inputStream.readLine()) != null) {
            String[] values = buffer.split(",");

            preparedStatement.setString(1, values[0].trim());
            preparedStatement.setFloat(2, Float.parseFloat(values[1].trim()));
            preparedStatement.setFloat(3, Float.parseFloat(values[2].trim()));
            preparedStatement.setString(4, values[3].trim());

            preparedStatement.execute();

        }
    } catch (SQLException e) {
        throw new GeoResolverException("Error while executing SQL query", e);
    } catch (IOException e) {
        throw new GeoResolverException("Error while accessing input file", e);
    }

    log.info("Finished populating Database for country data.");
    //should close all the connections for memory leaks.
}

From source file:org.apache.tika.cli.TikaCLIBatchIT.java

@Test
public void testDigester() throws Exception {
    /*/*from   w  w  w. ja  va 2 s.c o  m*/
            try {
    String[] params = {"-i", escape(testDataFile.getAbsolutePath()),
            "-o", escape(tempOutputDir.getAbsolutePath()),
            "-numConsumers", "10",
            "-J", //recursive Json
            "-t" //plain text in content
    };
    TikaCLI.main(params);
    reader = new InputStreamReader(
            new FileInputStream(new File(tempOutputDir, "test_recursive_embedded.docx.json")), UTF_8);
    List<Metadata> metadataList = JsonMetadataList.fromJson(reader);
    assertEquals(12, metadataList.size());
    assertEquals("59f626e09a8c16ab6dbc2800c685f772", metadataList.get(0).get("X-TIKA:digest:MD5"));
    assertEquals("22e6e91f408d018417cd452d6de3dede", metadataList.get(5).get("X-TIKA:digest:MD5"));
            } finally {
    IOUtils.closeQuietly(reader);
            }
    */
    String[] params = { "-i", testInputDirForCommandLine, "-o", tempOutputDirForCommandLine, "-numConsumers",
            "10", "-J", //recursive Json
            "-t", //plain text in content
            "-digest", "sha512" };
    runFramework(params);
    Path jsonFile = tempOutputDir.resolve("test_recursive_embedded.docx.json");
    try (Reader reader = Files.newBufferedReader(jsonFile, UTF_8)) {

        List<Metadata> metadataList = JsonMetadataList.fromJson(reader);
        assertEquals(12, metadataList.size());
        assertNotNull(metadataList.get(0).get("X-TIKA:digest:SHA512"));
        assertTrue(metadataList.get(0).get("X-TIKA:digest:SHA512").startsWith("ee46d973ee1852c01858"));
    }
}

From source file:de.upb.timok.models.PDTTA.java

public PDTTA(Path trebaPath) throws IOException {
    final BufferedReader inputReader = Files.newBufferedReader(trebaPath, StandardCharsets.UTF_8);
    String line = "";
    // 172 172 3 0,013888888888888892
    // from state ; to state ; symbol ; probability
    while ((line = inputReader.readLine()) != null) {
        final String[] lineSplit = line.split(" ");
        if (lineSplit.length == 4) {
            final int fromState = Integer.parseInt(lineSplit[0]);
            final int toState = Integer.parseInt(lineSplit[1]);
            final int symbol = Integer.parseInt(lineSplit[2]);
            final double probability = Double.parseDouble(lineSplit[3]);
            addTransition(fromState, toState, symbol, probability);
        } else if (lineSplit.length == 2) {
            final int state = Integer.parseInt(lineSplit[0]);
            final double finalProb = Double.parseDouble(lineSplit[1]);
            addFinalState(state, finalProb);
        }/*from w  w  w  . j  av  a2 s.  co m*/
    }
}

From source file:org.nuxeo.github.Analyzer.java

protected void load() {
    if (input == null) {
        input = Paths.get(System.getProperty("java.io.tmpdir"), "contributors.csv");
    }// ww w. j av  a  2 s.c  om
    if (!Files.isReadable(input)) {
        return;
    }
    try (CSVReader reader = new CSVReader(Files.newBufferedReader(input, Charset.defaultCharset()), '\t')) {
        // Check header
        String[] header = reader.readNext();
        if (!ArrayUtils.isEquals(CSV_HEADER, header)) {
            log.warn("Header mismatch " + Arrays.toString(header));
            return;
        }
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            Developer dev = parse(nextLine);
            if (dev.isAnonymous()) {
                developersByName.put(dev.getName(), dev);
            } else {
                developersByLogin.put(dev.getLogin(), dev);
            }
        }
        for (Developer dev : developersByLogin.values()) {
            for (String alias : dev.getAliases()) {
                if (developersByLogin.containsKey(alias)) {
                    developersByLogin.get(alias).updateWith(dev);
                }
            }
        }
        for (Developer dev : developersByName.values()) {
            for (String alias : dev.getAliases()) {
                if (developersByLogin.containsKey(alias)) {
                    developersByLogin.get(alias).updateWith(dev);
                }
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        try {
            Files.copy(input, input.resolveSibling(input.getFileName() + ".bak"),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e1) {
            log.error(e1.getMessage(), e1);
        }
    }
}

From source file:org.apache.zeppelin.interpreter.InterpreterSettingManager.java

private void loadFromFile() {
    if (!Files.exists(interpreterBindingPath)) {
        // nothing to read
        return;/*from ww w .j a v a2  s . c om*/
    }
    InterpreterInfoSaving infoSaving;
    try (BufferedReader json = Files.newBufferedReader(interpreterBindingPath, StandardCharsets.UTF_8)) {
        infoSaving = gson.fromJson(json, InterpreterInfoSaving.class);

        for (String k : infoSaving.interpreterSettings.keySet()) {
            InterpreterSetting setting = infoSaving.interpreterSettings.get(k);
            List<InterpreterInfo> infos = setting.getInterpreterInfos();

            // Convert json StringMap to Properties
            StringMap<String> p = (StringMap<String>) setting.getProperties();
            Properties properties = new Properties();
            for (String key : p.keySet()) {
                properties.put(key, p.get(key));
            }
            setting.setProperties(properties);

            // Always use separate interpreter process
            // While we decided to turn this feature on always (without providing
            // enable/disable option on GUI).
            // previously created setting should turn this feature on here.
            setting.getOption().setRemote(true);

            // Update transient information from InterpreterSettingRef
            InterpreterSetting interpreterSettingObject = interpreterSettingsRef.get(setting.getGroup());
            if (interpreterSettingObject == null) {
                logger.warn("can't get InterpreterSetting "
                        + "Information From loaded Interpreter Setting Ref - {} ", setting.getGroup());
                continue;
            }
            String depClassPath = interpreterSettingObject.getPath();
            setting.setPath(depClassPath);

            for (InterpreterInfo info : infos) {
                if (info.getEditor() == null) {
                    Map<String, Object> editor = getEditorFromSettingByClassName(interpreterSettingObject,
                            info.getClassName());
                    info.setEditor(editor);
                }
            }

            setting.setInterpreterGroupFactory(interpreterGroupFactory);

            loadInterpreterDependencies(setting);
            interpreterSettings.put(k, setting);
        }

        interpreterBindings.putAll(infoSaving.interpreterBindings);

        if (infoSaving.interpreterRepositories != null) {
            for (RemoteRepository repo : infoSaving.interpreterRepositories) {
                if (!dependencyResolver.getRepos().contains(repo)) {
                    this.interpreterRepositories.add(repo);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.structr.web.maintenance.DeployCommand.java

public Map<String, Object> readConfigMap(final Path pagesConf) {

    if (Files.exists(pagesConf)) {

        try (final Reader reader = Files.newBufferedReader(pagesConf, Charset.forName("utf-8"))) {

            return new HashMap<>(getGson().fromJson(reader, Map.class));

        } catch (IOException ioex) {
            logger.warn("", ioex);
        }// w  ww .  j  ava2 s  . c  om
    }

    return new HashMap<>();
}

From source file:com.fpuna.preproceso.PreprocesoTS.java

/**
 * Metodo estatico que lee el archivo y lo carga en una estructura de hash
 *
 * @param Archivo path del archivo//from   w w  w  .  j av  a 2s  .c o m
 * @return Hash con las sessiones leida del archivo de TrainigSet
 */
public static HashMap<String, SessionTS> leerArchivos(String Archivo, String sensor) {

    HashMap<String, SessionTS> SessionsTotal = new HashMap<String, SessionTS>();
    HashMap<String, String> actividades = new HashMap<String, String>();

    String sDirectorio = path;
    File dirList = new File(sDirectorio);

    if (dirList.exists()) { // Directorio existe 
        File[] ficheros = dirList.listFiles();
        for (int x = 0; x < ficheros.length; x++) {
            Path file = Paths.get(path + ficheros[x].getName());

            if (Files.exists(file) && Files.isReadable(file)) {

                try {
                    BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());

                    String line;
                    int cabecera = 0;

                    while ((line = reader.readLine()) != null) {
                        if (line.contentEquals("statusId | label")) {

                            //Leo todos las actividades  
                            while ((line = reader.readLine()) != null
                                    && !line.contentEquals("statusId|sensorName|value|timestamp")) {
                                String part[] = line.split("\\|");
                                actividades.put(part[0], part[1]);
                                SessionTS s = new SessionTS();
                                s.setActividad(part[1]);
                                SessionsTotal.put(part[0], s);
                            }
                            line = reader.readLine();
                        }

                        String lecturas[] = line.split("\\|");

                        if (lecturas[1].contentEquals(sensor)) {
                            Registro reg = new Registro();
                            reg.setSensor(lecturas[1]);
                            String[] values = lecturas[2].split("\\,");

                            if (values.length == 3) {
                                reg.setValor_x(Double.parseDouble(values[0].substring(1)));
                                reg.setValor_y(Double.parseDouble(values[1]));
                                reg.setValor_z(
                                        Double.parseDouble(values[2].substring(0, values[2].length() - 1)));
                            } else if (values.length == 5) {
                                reg.setValor_x(Double.parseDouble(values[0].substring(1)));
                                reg.setValor_y(Double.parseDouble(values[1]));
                                reg.setValor_z(Double.parseDouble(values[2]));
                                reg.setM_1(Double.parseDouble(values[3]));
                                reg.setM_2(Double.parseDouble(values[4].substring(0, values[4].length() - 1)));
                            }

                            reg.setTiempo(new Timestamp(Long.parseLong(lecturas[3])));

                            SessionTS s = SessionsTotal.get(lecturas[0]);
                            s.addRegistro(reg);
                            SessionsTotal.replace(lecturas[0], s);
                        }
                    }
                } catch (IOException ex) {
                    System.err.println("Okapu");
                    Logger.getLogger(PreprocesoTS.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }
    } else { //Directorio no existe 

    }

    return SessionsTotal;
}

From source file:io.personium.engine.source.FsServiceResourceSourceManager.java

/**
 * Get .pmeta in JSON format.//from w ww  .ja va  2 s .c o m
 * @param metaDirPath Directory path in which meta file to be acquired is stored
 * @return .pmeta in JSON format
 * @throws PersoniumEngineException Meta file not found.
 */
private JSONObject getMetaData(String metaDirPath) throws PersoniumEngineException {
    String separator = "";
    if (!metaDirPath.endsWith(File.separator)) {
        separator = File.separator;
    }
    File metaFile = new File(metaDirPath + separator + ".pmeta");
    JSONObject json = null;
    try (Reader reader = Files.newBufferedReader(metaFile.toPath(), Charsets.UTF_8)) {
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(reader);
    } catch (IOException | ParseException e) {
        // IO failure or JSON is broken
        log.info("Meta file not found or invalid (" + this.fsPath + ")");
        throw new PersoniumEngineException("500 Server Error",
                PersoniumEngineException.STATUSCODE_SERVER_ERROR);
    }
    return json;
}

From source file:org.apache.tika.batch.fs.FSBatchTestBase.java

public static String readFileToString(Path p, Charset cs) throws IOException {
    StringBuilder sb = new StringBuilder();
    try (BufferedReader r = Files.newBufferedReader(p, cs)) {
        String line = r.readLine();
        while (line != null) {
            sb.append(line).append("\n");
            line = r.readLine();/*from w  w  w.  j a  v a  2s  . com*/
        }
    }
    return sb.toString();
}

From source file:org.jboss.as.test.integration.logging.profiles.AbstractLoggingProfilesTestCase.java

@Test
public void noWarningTest() throws Exception {
    try {/*from w  w  w.  j a va  2 s  . co  m*/
        deploy(RUNTIME_NAME1, PROFILE1, false);
        deploy(RUNTIME_NAME2, PROFILE2, false);
        try (final BufferedReader reader = Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) {
            String line;
            while ((line = reader.readLine()) != null) {
                // Look for message id in order to support all languages.
                if (line.contains(PROFILE1) || line.contains(PROFILE2)) {
                    Assert.fail(
                            "Every deployment should have defined its own logging profile. But found this line in logs: "
                                    + line);
                }
            }
        }
    } finally {
        undeploy(RUNTIME_NAME1, RUNTIME_NAME2);
    }
}