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:org.jboss.as.test.integration.logging.perdeploy.Log4jPropertiesTestCase.java

@Test
public void logsTest() throws IOException {
    final String msg = "logTest: log4j.properties message";
    final int statusCode = getResponse(msg, Collections.singletonMap("includeLevel", "true"));
    assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);
    boolean trace = false;
    boolean fatal = false;
    String traceLine = msg + " - trace";
    String fatalLine = msg + " - fatal";
    try (final BufferedReader reader = Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) {
        String line;//from  ww w .  j a  v a  2 s . c  o m
        while ((line = reader.readLine()) != null) {
            if (line.contains(traceLine)) {
                trace = true;
            }
            if (line.contains(fatalLine)) {
                fatal = true;
            }
        }
    }
    Assert.assertTrue("Log file should contain line: " + traceLine, trace);
    Assert.assertTrue("Log file should contain line: " + fatalLine, fatal);
}

From source file:org.mda.bcb.tcgagsdata.create.ReadPlatform.java

public void readPlatform(String thePlatform) throws IOException, Exception {
    TcgaGSData.printWithFlag("readPlatform for " + thePlatform + " beginning");
    TcgaGSData.printWithFlag("readPlatform can consume excessive amounts of time and memory");
    mNumberOfGenes = 0;//ww  w.  j a  v a  2 s  . c  om
    TreeMap<String, Integer> geneMap = null;
    {
        ReadPlatform_GeneEq lg = new ReadPlatform_GeneEq(mReadPath);
        lg.getNamesGenes(thePlatform);
        mGenes = lg.mGenes;
        geneMap = TcgaGSData.buildIndexMap(lg.mGenes);
        mNumberOfGenes = lg.mSize;
    }
    mNumberOfSamples = 0;
    boolean found = false;
    long start = System.currentTimeMillis();
    TreeSet<File> dataFileList = new TreeSet<>();
    dataFileList.addAll(FileUtils.listFiles(new File(mReadPath, thePlatform),
            new WildcardFileFilter("matrix_data_*.tsv"), TrueFileFilter.INSTANCE));
    for (File input : dataFileList) {
        try (BufferedReader br = Files.newBufferedReader(Paths.get(input.getAbsolutePath()),
                Charset.availableCharsets().get("ISO-8859-1"))) {
            found = true;
            TcgaGSData.printWithFlag("readPlatform file=" + input.getAbsolutePath());
            // first line samples
            String line = br.readLine();
            TreeMap<String, Integer> sampleMap = TcgaGSData
                    .buildIndexMap(GSStringUtils.afterTab(line).split("\t", -1));
            if (0 == mNumberOfSamples) {
                mSamples = GSStringUtils.afterTab(line).split("\t", -1);
                mNumberOfSamples = mSamples.length;
                mGenesBySamplesValues = new double[mNumberOfGenes][mNumberOfSamples];
            } else {
                if (mNumberOfSamples != GSStringUtils.afterTab(line).split("\t", -1).length) {
                    throw new Exception("Expected sample count of " + mNumberOfSamples + " but found different "
                            + input.getAbsolutePath());
                }
            }
            line = br.readLine();
            while (null != line) {
                String gene = GSStringUtils.beforeTab(line);
                Integer intIndex = geneMap.get(gene);
                if (null != intIndex) {
                    int geneIndex = intIndex;
                    double[] valueList = convertToDouble(GSStringUtils.afterTab(line).split("\t", -1));
                    for (int x = 0; x < valueList.length; x++) {
                        int sampleIndex = sampleMap.get(mSamples[x]);
                        mGenesBySamplesValues[geneIndex][sampleIndex] = valueList[x];
                    }
                } else {
                    throw new Exception(
                            "readPlatform for " + thePlatform + " found unexpected 'gene' = " + gene);
                }
                line = br.readLine();
            }
        }
    }
    long finish = System.currentTimeMillis();
    TcgaGSData.printWithFlag(
            "readPlatform for " + thePlatform + " retrieved in " + ((finish - start) / 1000.0) + " seconds");
    if (false == found) {
        throw new Exception("readPlatform for " + thePlatform + " not found");
    } else {
        TcgaGSData.printWithFlag("write " + thePlatform + " to " + mWriteFile);
        writeFile();
    }
}

From source file:org.dbpedia.spotlight.lucene.index.external.utils.SSEIndexUtils.java

public static void decodeURI(Properties config, String toDecode, String decoded) {

    LOG.info("Start to decode URIs...");

    final BufferedReader reader;
    final BufferedWriter writer;
    final Path src = Paths.get(config.getProperty("org.dbpedia.spotlight.data." + toDecode, "").trim());
    final Path dst = Paths.get(config.getProperty("org.dbpedia.spotlight.data." + decoded, "").trim());
    String line;/* w  w  w .  j  a  v  a  2 s  . c o  m*/

    try {
        reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
        writer = Files.newBufferedWriter(dst, StandardCharsets.UTF_8);

        while ((line = reader.readLine()) != null) {
            line = line.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            line = line.replaceAll("\\+", "%2B");
            writer.write(URLDecoder.decode(line, "UTF-8"));
            writer.newLine();
        }
        writer.close();

        LOG.info("Done");

    } catch (Exception e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:org.opencb.biodata.formats.variant.annotation.io.VepFormatReader.java

@Override
public boolean open() {

    try {//from  w w w .j ava  2s.c o m
        this.path = Paths.get(this.filename);
        Files.exists(this.path);

        if (path.toFile().getName().endsWith(".gz")) {
            this.reader = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(new FileInputStream(path.toFile()))));
        } else {
            this.reader = Files.newBufferedReader(path, Charset.defaultCharset());
        }

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

    return true;
}

From source file:filtercdnafile.CreateCdnaProteinFiles.java

/**
 * reads the protein file and writes the lines with the same id as in the proteinList in to
 * a new file.//from   ww w.  j av  a2  s. c  om
 * @throws ParseException
 * @throws IOException 
 */
private void readProteinFasta() throws ParseException, IOException {
    Pattern re = Pattern.compile("(?<=>)ENSRNOP\\d+");
    FileWriter writer = new FileWriter();
    Charset charset = Charset.forName("US-ASCII");
    try (BufferedReader reader = Files.newBufferedReader(proteinFile, charset)) {
        String line;
        writer.OpenFile(newFile);
        while ((line = reader.readLine()) != null) {
            if (line.contains(">")) {
                if (ID.isEmpty() == false & sequence.isEmpty() == false) {
                    //Skips the line if it is a  mitochondiral protein. 
                    if (!ID.contains("RGSC3.4:MT")) {
                        writer.writeLine(ID + "\t" + sequence);
                    }
                }
                ID = line;
                sequence = "";

            } else {
                sequence += line.trim();
            }
        }
        writer.writeLine(ID + "\t" + sequence);
        writer.CloseFile();
    } catch (IOException x) {
        System.err.format("IOException: %s%n", x);
    }
}

From source file:com.shekhargulati.reactivex.rxokhttp.SslCertificates.java

private SslCertificates(final Builder builder) throws SslCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new SslCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }/*from   w w  w . j a v a2  s . com*/

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (java.security.cert.CertificateException | IOException | NoSuchAlgorithmException
            | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException
            | KeyManagementException e) {
        throw new SslCertificateException(e);
    }
}

From source file:com.pivotal.gfxd.demo.loader.LoadRunner.java

public void run(final String CSV_FILE) {

    List<String[]> lines = new LinkedList<>();
    String timestamp = null;//w w  w.ja v  a 2s  .  c o m

    try (BufferedReader br = Files.newBufferedReader(Paths.get(CSV_FILE), StandardCharsets.UTF_8)) {

        // Lines are in this form:
        // id, timestamp, value, property, plug_id, household_id, house_id

        for (String line = null; (line = br.readLine()) != null;) {
            String[] split = line.split(",");

            int houseId = Integer.parseInt(split[6]);
            if (houseId >= maxHouseId) {
                continue;
            }

            // We only care about 'load' values at the moment
            int property = Integer.parseInt(split[3]);
            if (property != 1) {
                continue;
            }

            // first iteration
            if (timestamp == null) {
                timestamp = split[1];
                lines.add(split);
                startTime = Long.parseLong(timestamp);
                // The stream of events need to appear as though they started
                // 'boostTime' seconds ago.
                deltaAdjust = (System.currentTimeMillis() / 1000) - startTime - boostTime;

            } else {
                // batch same timestamp objects
                if (timestamp.equals(split[1])) {
                    lines.add(split);

                } else {

                    // send batched records and create a new batch
                    this.asyncInsertBatch(lines, Long.parseLong(timestamp) + deltaAdjust);
                    lines = new LinkedList<>();
                    lines.add(split);
                    timestamp = split[1];
                }
            }
        }
        // insert last pending batch
        this.asyncInsertBatch(lines, Long.parseLong(timestamp) + deltaAdjust);

    } catch (IOException ioex) {
        logger.error("An error occurred during batch insertion or the file was not accessible. Message: "
                + ioex.getMessage());
    }

}

From source file:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new DockerCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }//w  ww . j  a  va 2 s.c om

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:com.digitalpebble.storm.crawler.spout.FileSpout.java

@SuppressWarnings("rawtypes")
@Override/*from w w w.  ja  va2  s.c  o  m*/
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    _collector = collector;

    for (String inputFile : _inputFiles) {
        Path inputPath = Paths.get(inputFile);
        try (BufferedReader reader = Files.newBufferedReader(inputPath, StandardCharsets.UTF_8)) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (StringUtils.isBlank(line))
                    continue;
                toPut.add(line.getBytes(StandardCharsets.UTF_8));
            }
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }
    }
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Return a {@link java.util.Properties} read from the specified string file path.
 *
 * @param file the {@link java.nio.file.Path } name of the file to read the properties from.
 * @return the {@link java.util.Properties} instance.
 * @throws IOException the {@link java.io.IOException} if the file was not found or there were problems reading from it.
 *//*from   w w w. j  a v a  2  s.  c om*/
default Properties readFromFile(File file) throws IOException {

    Validate.notNull(file);

    if (Files.exists(file.toPath()))
        throw new FileNotFoundException("File at " + file.getPath() + " was not found");

    Properties properties = new Properties();
    try {

        properties.load(Files.newBufferedReader(file.toPath(), Charset.defaultCharset()));
    } catch (IOException e) {
        Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e.getCause());
        throw e;
    }

    return properties;
}