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:com.dieterholvoet.scoutsapp.util.CSVParser.java

public void readFile() {
    this.readFileThread = new Thread() {

        @Override//from w w  w. j a  v a  2 s . c  om
        public void run() {
            if (selectedFile != null && !"".equals(selectedFile)) {
                File file = new File(selectedFile);
                BufferedReader reader = null;
                BufferedReader sizeReader = null;
                try {
                    reader = Files.newBufferedReader(file.toPath());
                    sizeReader = Files.newBufferedReader(file.toPath());

                    while (sizeReader.readLine() != null)
                        count++;
                    sizeReader.close();

                    String uitgelezenRegel = reader.readLine();
                    parseColumnsFromString(uitgelezenRegel);
                    uitgelezenRegel = reader.readLine();

                    while (uitgelezenRegel != null) {
                        uitgelezenRegel = uitgelezenRegel.replaceAll("\"", "");
                        Lid nieuwLid = parseLidFromString(uitgelezenRegel);
                        ArrayList<ContactPersoon> cp = parseContactPersonenFromString(uitgelezenRegel);

                        if (nieuwLid.isLeiding()) {
                            // is Leiding
                            if (LeidingDAO.leidingExists(nieuwLid.getLidnr())) {
                                progressUpdate("Bestaande leiding bijwerken: " + nieuwLid.toString());
                                LeidingDAO.updateLeiding(nieuwLid);

                            } else {
                                progressUpdate("Nieuwe leiding toevoegen: " + nieuwLid.toString());
                                LeidingDAO.voegLeidingToe(nieuwLid);
                            }

                        } else {
                            // is Lid
                            if (LidDAO.lidExists(nieuwLid.getLidnr())) {
                                progressUpdate("Bestaand lid bijwerken: " + nieuwLid.toString());
                                LidDAO.updateLid(nieuwLid);

                            } else {
                                progressUpdate("Nieuw lid toevoegen: " + nieuwLid.toString());
                                LidDAO.voegLidToe(nieuwLid);
                            }
                        }

                        for (ContactPersoon contact : cp) {
                            ContactPersoon test = ContactPersoonDAO
                                    .getContactPersoonByName(contact.getVoornaam(), contact.getAchternaam());
                            if (test == null) {
                                ContactPersoonDAO.voegContactPersoonToe(contact, nieuwLid);

                            } else {
                                ContactPersoonDAO.voegContactPersoonRelatieToe(test, nieuwLid);
                            }
                        }

                        uitgelezenRegel = reader.readLine();
                        progress++;
                    }

                } catch (IOException ex) {
                    Logger.getLogger(WerkstukGUI.class.getName()).log(Level.SEVERE, "Error while reading file.",
                            ex);
                    JOptionPane.showMessageDialog(parent, "Error while reading file.");

                } finally {
                    try {
                        if (reader != null) {
                            reader.close();
                        }

                    } catch (IOException ex) {
                        Logger.getLogger(CSVParser.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    progressUpdate("Uitlezen voltooid.");
                    parent.CSVParserCallback();
                }

            } else {
                Logger.getLogger(WerkstukGUI.class.getName()).log(Level.SEVERE, "Choose a file first!");
            }
        }
    };

    this.readFileThread.start();
}

From source file:it.units.malelab.ege.util.DUMapper.java

private static double[][][] getGomeaData(String baseDir, String fileNamePattern, int generations,
        int genotypeSize) throws IOException {
    double[][] usages = new double[generations][];
    Set<Character>[] domains = new Set[genotypeSize];
    Multiset<Character>[][] symbols = new Multiset[generations][];
    for (int i = 0; i < genotypeSize; i++) {
        domains[i] = new HashSet<>();
    }/*from  www.ja  v a2s .  c o  m*/
    for (int g = 0; g < generations; g++) {
        symbols[g] = new Multiset[genotypeSize];
        for (int i = 0; i < genotypeSize; i++) {
            symbols[g][i] = HashMultiset.create();
        }
        usages[g] = new double[genotypeSize];
        BufferedReader reader = Files.newBufferedReader(
                FileSystems.getDefault().getPath(baseDir, String.format(fileNamePattern, g)));
        String line;
        int populationSize = 0;
        while ((line = reader.readLine()) != null) {
            populationSize = populationSize + 1;
            String[] pieces = line.split(" ");
            String genotype = pieces[0];
            for (int i = 0; i < genotypeSize; i++) {
                domains[i].add(genotype.charAt(i));
                symbols[g][i].add(genotype.charAt(i));
            }
            for (int i = 2; i < pieces.length; i++) {
                int intronIndex = Integer.parseInt(pieces[i]);
                usages[g][intronIndex] = usages[g][intronIndex] + 1;
            }
        }
        for (int i = 0; i < genotypeSize; i++) {
            usages[g][i] = (populationSize - usages[g][i]) / populationSize;
        }
        reader.close();
    }
    double[][] diversities = new double[generations][];
    for (int g = 0; g < generations; g++) {
        diversities[g] = new double[genotypeSize];
        for (int i = 0; i < genotypeSize; i++) {
            diversities[g][i] = Utils.multisetDiversity(symbols[g][i], domains[i]);
        }
    }
    return new double[][][] { diversities, usages };
}

From source file:org.opennms.features.newts.converter.NewtsConverter.java

private void processStoreByGroupResource(final Path path) {
    // Load the 'ds.properties' for the current path
    final Properties ds = new Properties();
    try (final BufferedReader r = Files.newBufferedReader(path.resolve("ds.properties"))) {
        ds.load(r);//from ww  w. j  a v a2s.  com

    } catch (final IOException e) {
        LOG.error("No group information found - please verify storageStrategy settings");
        return;
    }

    // Get all groups declared in the ds.properties and process the RRD files
    Sets.newHashSet(Iterables.transform(ds.values(), Object::toString))
            .forEach(group -> this.executor.execute(() -> processResource(path, group, group)));
}

From source file:org.opennms.features.newts.converter.NewtsConverter.java

private void processStoreByMetricResource(final Path metaPath) {
    // Use the containing directory as resource path
    final Path path = metaPath.getParent();

    // Extract the metric name from the file name
    final String metric = FilenameUtils.removeExtension(metaPath.getFileName().toString());

    // Load the '.meta' file to get the group name
    final Properties meta = new Properties();
    try (final BufferedReader r = Files.newBufferedReader(metaPath)) {
        meta.load(r);//from   w  w w  . ja  va  2  s  .com

    } catch (final IOException e) {
        LOG.error("Failed to read .meta file: {}", metaPath, e);
        return;
    }

    final String group = meta.getProperty("GROUP");
    if (group == null) {
        LOG.warn("No group information found - please verify storageStrategy settings");
        return;
    }

    // Process the resource
    this.executor.execute(() -> this.processResource(path, metric, group));
}

From source file:it.units.malelab.ege.util.DUMapper.java

private static double[][][] getNeatData(String baseDir, String fileNamePattern, int generations)
        throws IOException {
    List<List<Map<Integer, Pair<Double, Double>>>> data = new ArrayList<>();
    int maxInnovationNumber = 0;
    for (int g = 0; g < generations; g++) {
        List<Map<Integer, Pair<Double, Double>>> currentPopulation = new ArrayList<>();
        BufferedReader reader = Files.newBufferedReader(
                FileSystems.getDefault().getPath(baseDir, String.format(fileNamePattern, g + 1)));
        String line;/* w  ww.j  a v  a 2  s . c o  m*/
        boolean isInPopulation = false;
        Map<Integer, Pair<Double, Double>> currentIndividual = null;
        while ((line = reader.readLine()) != null) {
            if (line.equals("[NEAT-POPULATION:SPECIES]")) {
                isInPopulation = true;
                continue;
            }
            if (!isInPopulation) {
                continue;
            }
            if (line.startsWith("\"g\"")) {
                if (currentIndividual != null) {
                    //save current individual
                    currentPopulation.add(currentIndividual);
                }
                currentIndividual = new HashMap<>();
            }
            if (line.startsWith("\"n\"") || line.startsWith("\"l\"")) {
                String[] pieces = line.split(",");
                int innovationNumber = Integer.parseInt(pieces[pieces.length - 1]);
                maxInnovationNumber = Math.max(innovationNumber, maxInnovationNumber);
                double used = 1;
                double value = 1;
                if (line.startsWith("\"l\"")) {
                    value = Double.parseDouble(pieces[pieces.length - 2]);
                    used = Double.parseDouble(pieces[2]);
                }
                currentIndividual.put(innovationNumber, new Pair<>(used, value));
            }
        }
        reader.close();
        data.add(currentPopulation);
    }
    //populate arrays
    double[][] usages = new double[generations][];
    double[][] diversities = new double[generations][];
    for (int g = 0; g < generations; g++) {
        usages[g] = new double[maxInnovationNumber];
        diversities[g] = new double[maxInnovationNumber];
        List<Map<Integer, Pair<Double, Double>>> currentPopulation = data.get(g);
        //populate usages
        double[][] values = new double[maxInnovationNumber][];
        double[] localUsages = new double[maxInnovationNumber];
        for (int i = 0; i < maxInnovationNumber; i++) {
            values[i] = new double[currentPopulation.size()];
        }
        for (int p = 0; p < currentPopulation.size(); p++) {
            for (int i = 0; i < maxInnovationNumber; i++) {
                double value = 0;
                double used = 0;
                if (currentPopulation.get(p).containsKey(i)) {
                    Pair<Double, Double> pair = currentPopulation.get(p).get(i);
                    value = pair.getSecond();
                    used = pair.getFirst();
                }
                values[i][p] = value;
                localUsages[i] = localUsages[i] + used;
            }
        }
        for (int i = 0; i < maxInnovationNumber; i++) {
            usages[g][i] = localUsages[i] / (double) currentPopulation.size();
            diversities[g][i] = normalizedVar(values[i]);
        }
    }
    return new double[][][] { diversities, usages };
}

From source file:com.webtide.jetty.load.generator.jenkins.LoadGeneratorBuilder.java

protected void parseTimeValues(FilePath workspace, Path responseTimeResultFilePath,
        List<Resource.NodeListener> nodeListeners) throws Exception {
    Path responseTimeResultFile = Files.createTempFile("loadgenerator_result_responsetime", ".csv");

    workspace.child(responseTimeResultFilePath.toString())
            .copyTo(Files.newOutputStream(responseTimeResultFile));

    CSVParser csvParser = new CSVParser(Files.newBufferedReader(responseTimeResultFile),
            CSVFormat.newFormat('|'));

    csvParser.forEach(strings -> {/* www  .j av a 2 s  .c o m*/
        Values values = new Values() //
                .eventTimestamp(Long.parseLong(strings.get(0))) //
                .method(strings.get(1)) //
                .path(strings.get(2)) //
                .status(Integer.parseInt(strings.get(3))) //
                .size(Long.parseLong(strings.get(4))) //
                .responseTime(Long.parseLong(strings.get(5))) //
                .latencyTime(Long.parseLong(strings.get(6)));

        for (Resource.NodeListener listener : nodeListeners) {
            listener.onResourceNode(values.getInfo());
        }
    });

    Files.deleteIfExists(responseTimeResultFile);
}

From source file:it.units.malelab.ege.util.DUMapper.java

private static double[][][] getNeatData2(String baseDir, String fileNamePattern, int generations)
        throws IOException {
    List<List<Map<Integer, Pair<Double, Double>>>> data = new ArrayList<>();
    int maxInnovationNumber = 0;
    for (int g = 0; g < generations; g++) {
        List<Map<Integer, Pair<Double, Double>>> currentPopulation = new ArrayList<>();
        BufferedReader reader = Files.newBufferedReader(
                FileSystems.getDefault().getPath(baseDir, String.format(fileNamePattern, g + 1)));
        String line;/*from  w ww  . j  a v  a 2  s  .  com*/
        boolean isInPopulation = false;
        Map<Integer, Pair<Double, Double>> currentIndividual = null;
        Set<Integer> currentIndividualConnectedNodes = new HashSet<>();
        while ((line = reader.readLine()) != null) {
            if (line.equals("[NEAT-POPULATION:SPECIES]")) {
                isInPopulation = true;
                continue;
            }
            if (!isInPopulation) {
                continue;
            }
            if (line.startsWith("\"g\"")) {
                if (currentIndividual != null) {
                    //compute data for nodes
                    for (int usedNode : currentIndividualConnectedNodes) {
                        currentIndividual.put(usedNode, new Pair<>(1d, 1d));
                    }
                    //save current individual
                    currentPopulation.add(currentIndividual);
                }
                currentIndividual = new HashMap<>();
                currentIndividualConnectedNodes.clear();
            }
            if (line.startsWith("\"n\"") || line.startsWith("\"l\"")) {
                String[] pieces = line.split(",");
                int innovationNumber = Integer.parseInt(pieces[pieces.length - 1]);
                maxInnovationNumber = Math.max(innovationNumber, maxInnovationNumber);
                double used = 0;
                double value = 0;
                if (line.startsWith("\"l\"")) {
                    value = Double.parseDouble(pieces[pieces.length - 2]);
                    used = Double.parseDouble(pieces[2]);
                    //get connected nodes
                    if (used == 1) {
                        currentIndividualConnectedNodes.add(Integer.parseInt(pieces[3]));
                        currentIndividualConnectedNodes.add(Integer.parseInt(pieces[4]));
                    }
                }
                currentIndividual.put(innovationNumber, new Pair<>(used, value));
            }
        }
        reader.close();
        data.add(currentPopulation);
    }
    //populate arrays
    double[][] usages = new double[generations][];
    double[][] diversities = new double[generations][];
    for (int g = 0; g < generations; g++) {
        usages[g] = new double[maxInnovationNumber];
        diversities[g] = new double[maxInnovationNumber];
        List<Map<Integer, Pair<Double, Double>>> currentPopulation = data.get(g);
        //populate usages
        double[][] values = new double[maxInnovationNumber][];
        double[] localUsages = new double[maxInnovationNumber];
        for (int i = 0; i < maxInnovationNumber; i++) {
            values[i] = new double[currentPopulation.size()];
        }
        for (int p = 0; p < currentPopulation.size(); p++) {
            for (int i = 0; i < maxInnovationNumber; i++) {
                double value = 0;
                double used = 0;
                if (currentPopulation.get(p).containsKey(i)) {
                    Pair<Double, Double> pair = currentPopulation.get(p).get(i);
                    value = pair.getSecond();
                    used = pair.getFirst();
                }
                values[i][p] = value;
                localUsages[i] = localUsages[i] + used;
            }
        }
        for (int i = 0; i < maxInnovationNumber; i++) {
            usages[g][i] = localUsages[i] / (double) currentPopulation.size();
            diversities[g][i] = normalizedVar(values[i]);
        }
    }
    return new double[][][] { diversities, usages };
}

From source file:org.opennms.features.newts.converter.NewtsConverter.java

private void processStringsProperties(final Path path) {
    try {//www.jav a2  s.  c  o m
        // Find an process all 'strings.properties' files
        Files.walk(path).filter(p -> p.endsWith("strings.properties")).forEach(p -> {
            final Properties properties = new Properties();
            try (final BufferedReader r = Files.newBufferedReader(p)) {
                properties.load(r);

            } catch (final IOException e) {
                throw Throwables.propagate(e);
            }

            final ResourcePath resourcePath = buildResourcePath(p.getParent());
            if (resourcePath == null) {
                return;
            }

            this.injectStringPropertiesToNewts(resourcePath, Maps.fromProperties(properties));
        });

    } catch (Exception e) {
        LOG.error("Error while reading string.properties", e);
        return;
    }
}

From source file:org.apache.openmeetings.web.room.wb.WbPanel.java

@Override
public void sendFileToWb(final BaseFileItem fi, boolean clean) {
    if (isVisible() && fi.getId() != null) {
        Whiteboards wbs = wbm.get(roomId);
        String wuid = randomUUID().toString();
        Whiteboard wb = wbs.get(wbs.getActiveWb());
        if (wb == null) {
            return;
        }/*w  ww .  j a v a 2 s.  c  o m*/
        switch (fi.getType()) {
        case Folder:
            //do nothing
            break;
        case WmlFile: {
            File f = fi.getFile();
            if (f.exists() && f.isFile()) {
                try (BufferedReader br = Files.newBufferedReader(f.toPath())) {
                    final boolean[] updated = { false };
                    JSONArray arr = getArray(new JSONObject(new JSONTokener(br)), o -> {
                        wb.put(o.getString("uid"), o);
                        updated[0] = true;
                        return addFileUrl(rp.getClient(), wbs.getUid(), o, _f -> updateWbSize(wb, _f));
                    });
                    if (updated[0]) {
                        wbm.update(roomId, wb);
                    }
                    sendWbAll(WbAction.setSize, getAddWbJson(wb));
                    sendWbAll(WbAction.load, getObjWbJson(wb.getId(), arr));
                } catch (Exception e) {
                    log.error("Unexpected error while loading WB", e);
                }
            }
        }
            break;
        case PollChart:
            break;
        default: {
            JSONObject file = new JSONObject().put(ATTR_FILE_ID, fi.getId())
                    .put(ATTR_FILE_TYPE, fi.getType().name()).put("count", fi.getCount())
                    .put(ATTR_TYPE, "image").put("left", UPLOAD_WB_LEFT).put("top", UPLOAD_WB_TOP)
                    .put(ATTR_WIDTH, fi.getWidth() == null ? DEFAULT_WIDTH : fi.getWidth())
                    .put(ATTR_HEIGHT, fi.getHeight() == null ? DEFAULT_HEIGHT : fi.getHeight()).put("uid", wuid)
                    .put(ATTR_SLIDE, wb.getSlide());
            if (FileItem.Type.Video == fi.getType() || FileItem.Type.Recording == fi.getType()) {
                file.put(ATTR_TYPE, "video");
                file.put(PARAM_STATUS, new JSONObject().put("paused", true).put("pos", 0.0).put(PARAM_UPDATED,
                        System.currentTimeMillis()));
            }
            final String ruid = wbs.getUid();
            if (clean) {
                clearAll(roomId, wb.getId());
            }
            wb.put(wuid, file);
            updateWbSize(wb, fi);
            wbm.update(roomId, wb);
            sendWbAll(WbAction.setSize, getAddWbJson(wb));
            WbWebSocketHelper.sendWbFile(roomId, wb.getId(), ruid, file, fi);
        }
            break;
        }
    }
}

From source file:net.minecraftforge.common.crafting.CraftingHelper.java

private static void loadFactories(ModContainer mod) {
    FileSystem fs = null;// w ww. j  av  a 2 s .  c  om
    BufferedReader reader = null;
    try {
        JsonContext ctx = new JsonContext(mod.getModId());
        Path fPath = null;
        if (mod.getSource().isFile()) {
            fs = FileSystems.newFileSystem(mod.getSource().toPath(), null);
            fPath = fs.getPath("/assets/" + ctx.getModId() + "/recipes/_factories.json");
        } else if (mod.getSource().isDirectory()) {
            fPath = mod.getSource().toPath().resolve("assets/" + ctx.getModId() + "/recipes/_factories.json");
        }
        if (fPath != null && Files.exists(fPath)) {
            reader = Files.newBufferedReader(fPath);
            JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class);
            loadFactories(json, ctx);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fs);
        IOUtils.closeQuietly(reader);
    }
}