Example usage for java.io Reader close

List of usage examples for java.io Reader close

Introduction

In this page you can find the example usage for java.io Reader close.

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:my.FileBasedTestCase.java

/** Assert that the content of a file is equal to that in a char[]. */
protected void assertEqualContent(char[] c0, File file) throws IOException {
    Reader ir = new java.io.FileReader(file);
    int count = 0, numRead = 0;
    char[] c1 = new char[c0.length];
    try {/*from  www  .j a  va  2 s  . c  o m*/
        while (count < c0.length && numRead >= 0) {
            numRead = ir.read(c1, count, c0.length);
            count += numRead;
        }
        assertEquals("Different number of chars: ", c0.length, count);
        for (int i = 0; i < count; i++) {
            assertEquals("char " + i + " differs", c0[i], c1[i]);
        }
    } finally {
        ir.close();
    }
}

From source file:com.cotrino.langnet.GenerateVisualization.java

private double[] calculateSimilarity(File logFile) throws IOException {

    int i = 0;//  w w w.j  a v  a 2  s  . c  om
    double total = 0.0;
    Reader reader = new FileReader(logFile);
    CSVParser parser = new CSVParser(reader, csvFormat);
    for (CSVRecord record : parser) {
        try {
            double similarity = Double.parseDouble(record.get("Similarity"));
            total += similarity;
            i++;
        } catch (NumberFormatException e) {
            logger.error("At " + logFile.getName() + ", failed line: " + record.toString());
        }
    }
    parser.close();
    reader.close();
    return new double[] { (total / i), i };

}

From source file:com.cloudera.sqoop.io.TestLobFile.java

/**
 * Run a test where we read only a fraction of the first record,
 * but then read the second record completely. Verify that we
 * can re-align on a record boundary correctly. This test requires
 * at least 3 records./*from w  w w  .ja v a  2 s.c o m*/
 * @param p the path to the file to create.
 * @param firstLine the first line of the first reord
 * @param records All of the records to write to the file.
 */
private void runLineAndRecordTest(Path p, String firstLine, String... records) throws Exception {

    assertTrue("This test requires 3+ records", records.length > 2);

    writeClobFile(p, null, records);

    LobFile.Reader reader = LobFile.open(p, conf);

    // We should not yet be aligned.
    assertFalse(reader.isRecordAvailable());
    assertTrue(reader.next());
    // Now we should be.
    assertTrue(reader.isRecordAvailable());

    // Read just one line from the record.
    Reader r = reader.readClobRecord();
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    assertEquals(firstLine, line);

    br.close();
    r.close();

    // We should no longer be aligned on a record start.
    assertFalse(reader.isRecordAvailable());

    // We should now be able to get to record two.
    assertTrue(reader.next());

    // This should be nicely aligned even if the first record was not
    // completely consumed by a client.
    r = reader.readClobRecord();
    CharBuffer buf = CharBuffer.allocate(records[1].length());
    r.read(buf);
    r.close();
    char[] chars = buf.array();
    String s = new String(chars);
    assertEquals(records[1], s);

    // Close the reader before we consume the entire file. 
    reader.close();
    assertFalse(reader.isRecordAvailable());
}

From source file:com.lexicalintelligence.admin.get.MapGetRequest.java

@SuppressWarnings("unchecked")
public <T extends LexicalResponse> T execute() {
    MapGetResponse searchResponse;/*from   ww  w .ja  v a2s  . co  m*/
    Reader reader = null;
    try {
        HttpResponse response = client.getHttpClient().execute(new HttpGet(client.getUrl() + PATH + getPath()));
        reader = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8);
        Map<String, String> items = client.getObjectMapper().readValue(reader,
                new TypeReference<Map<String, String>>() {
                });
        searchResponse = new MapGetResponse(true);
        searchResponse.setItems(items);
    } catch (Exception e) {
        searchResponse = new MapGetResponse(false);
        log.error(e);
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            log.error(e);
        }
    }
    return (T) searchResponse;
}

From source file:com.silverpeas.jcrutil.BetterRepositoryFactoryBean.java

/**
 * Load a Resource as a String.//from  w  ww.  ja v  a 2 s. com
 *
 * @param config the resource
 * @return the String filled with the content of the Resource
 * @throws IOException
 */
protected String getConfiguration(Resource config) throws IOException {
    StringWriter out = new StringWriter();
    Reader reader = null;
    try {
        reader = new InputStreamReader(config.getInputStream(), Charsets.UTF_8);
        char[] buffer = new char[8];
        int c;
        while ((c = reader.read(buffer)) > 0) {
            out.write(buffer, 0, c);
        }
        return out.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

private JsonElement parseResponse(InputStream response) throws IOException {
    Reader reader = new InputStreamReader(response, Consts.UTF_8);
    reader.skip(5);//from  ww w. j  a va 2 s  . c o  m
    try {
        return new JsonParser().parse(reader);
    } catch (JsonSyntaxException jse) {
        throw new IOException(String.format("Couldn't parse response: %n%s", CharStreams.toString(reader)),
                jse);
    } finally {
        reader.close();
    }
}

From source file:com.bigdata.gom.RemoteGOMTestCase.java

protected void print(final URL n3) throws IOException {
    if (log.isInfoEnabled()) {
        InputStream in = n3.openConnection().getInputStream();
        Reader reader = new InputStreamReader(in);
        try {//from  w  w w . j  a  va2  s .  co  m
            char[] buf = new char[256];
            int rdlen = 0;
            while ((rdlen = reader.read(buf)) > -1) {
                if (rdlen == 256)
                    System.out.print(buf);
                else
                    System.out.print(new String(buf, 0, rdlen));
            }
        } finally {
            reader.close();
        }
    }
}

From source file:org.psikeds.knowledgebase.xml.impl.XMLParser.java

/**
 * Parse the specified XML and unmarshal it to JAXB-Object-Structures.
 * Suitable for big XML files by using JAXB combination with StAX.<br>
 * All classes in the specified package can be parsed.<br>
 * /*from  w w  w. j  av a2s  . com*/
 * @return Total number of unmarshalled XML-Elements
 * @throws XMLStreamException
 * @throws SAXException
 * @throws JAXBException
 * @throws IOException
 */
@Override
public long parseXmlElements() throws XMLStreamException, SAXException, JAXBException, IOException {
    Reader xml = null;
    try {
        xml = createXmlReader();
        return parseXmlElements(xml);
    } finally {
        if (xml != null) {
            try {
                xml.close();
            } catch (final IOException ex) {
                // ignore
            } finally {
                xml = null;
            }
        }
    }
}

From source file:edu.uci.ics.asterix.test.optimizer.OptimizerTest.java

@Test
public void test() throws Exception {
    try {//from  www .j a  va2s  .  co  m
        String queryFileShort = queryFile.getPath().substring(PATH_QUERIES.length())
                .replace(SEPARATOR.charAt(0), '/');
        if (!only.isEmpty()) {
            boolean toRun = TestHelper.isInPrefixList(only, queryFileShort);
            if (!toRun) {
                LOGGER.info("SKIP TEST: \"" + queryFile.getPath()
                        + "\" \"only.txt\" not empty and not in \"only.txt\".");
            }
            Assume.assumeTrue(toRun);
        }
        boolean skipped = TestHelper.isInPrefixList(ignore, queryFileShort);
        if (skipped) {
            LOGGER.info("SKIP TEST: \"" + queryFile.getPath() + "\" in \"ignore.txt\".");
        }
        Assume.assumeTrue(!skipped);

        LOGGER.info("RUN TEST: \"" + queryFile.getPath() + "\"");
        Reader query = new BufferedReader(new InputStreamReader(new FileInputStream(queryFile), "UTF-8"));
        PrintWriter plan = new PrintWriter(actualFile);
        AsterixJavaClient asterix = new AsterixJavaClient(
                AsterixHyracksIntegrationUtil.getHyracksClientConnection(), query, plan);
        try {
            asterix.compile(true, false, false, true, true, false, false);
        } catch (AsterixException e) {
            plan.close();
            query.close();
            throw new Exception("Compile ERROR for " + queryFile + ": " + e.getMessage(), e);
        }
        plan.close();
        query.close();

        BufferedReader readerExpected = new BufferedReader(
                new InputStreamReader(new FileInputStream(expectedFile), "UTF-8"));
        BufferedReader readerActual = new BufferedReader(
                new InputStreamReader(new FileInputStream(actualFile), "UTF-8"));

        String lineExpected, lineActual;
        int num = 1;
        try {
            while ((lineExpected = readerExpected.readLine()) != null) {
                lineActual = readerActual.readLine();
                // Assert.assertEquals(lineExpected, lineActual);
                if (lineActual == null) {
                    throw new Exception("Result for " + queryFile + " changed at line " + num + ":\n< "
                            + lineExpected + "\n> ");
                }
                if (!lineExpected.equals(lineActual)) {
                    throw new Exception("Result for " + queryFile + " changed at line " + num + ":\n< "
                            + lineExpected + "\n> " + lineActual);
                }
                ++num;
            }
            lineActual = readerActual.readLine();
            // Assert.assertEquals(null, lineActual);
            if (lineActual != null) {
                throw new Exception(
                        "Result for " + queryFile + " changed at line " + num + ":\n< \n> " + lineActual);
            }
            LOGGER.info("Test \"" + queryFile.getPath() + "\" PASSED!");
            actualFile.delete();
        } finally {
            readerExpected.close();
            readerActual.close();
        }
    } catch (Exception e) {
        if (!(e instanceof AssumptionViolatedException)) {
            LOGGER.severe("Test \"" + queryFile.getPath() + "\" FAILED!");
            throw new Exception("Test \"" + queryFile.getPath() + "\" FAILED!", e);
        } else {
            throw e;
        }
    }
}

From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java

private void initialize() {
    this.init = true;

    try {/* www.  java  2  s .co m*/
        InputStream in = new FileInputStream(getSourceFile());
        ArrayList<String> itemList = new ArrayList<String>();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        String item = null;
        final int bufLength = 1024;
        char[] buffer = new char[bufLength];
        int readReturn;
        int count = 0;

        ZipEntry zipentry;
        ZipInputStream zipinputstream = new ZipInputStream(in);

        while ((zipentry = zipinputstream.getNextEntry()) != null) {
            count++;
            StringWriter sw = new StringWriter();
            Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8"));

            while ((readReturn = reader.read(buffer)) != -1) {
                sw.write(buffer, 0, readReturn);
            }

            item = new String(sw.toString());
            itemList.add(item);
            this.fileNames.add(zipentry.getName());

            reader.close();
            zipinputstream.closeEntry();

        }

        this.logger.debug("Zip file contains " + count + "elements");
        zipinputstream.close();
        this.counter = 0;

        this.originalData = byteArrayOutputStream.toByteArray();
        this.items = itemList.toArray(new String[] {});
        this.length = this.items.length;
    } catch (Exception e) {
        this.logger.error("Could not read zip File: " + e.getMessage());
        throw new RuntimeException("Error reading input stream", e);
    }
}