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:com.cotrino.langnet.GenerateVisualization.java

private void getLanguages(String file) throws IOException {

    amountWordsPerLanguage = new HashMap<String, Integer>();

    Reader reader = new FileReader(file);
    CSVParser parser = new CSVParser(reader, csvFormat);
    for (CSVRecord record : parser) {
        String language = record.get("Language");
        int words = Integer.parseInt(record.get("Words"));
        amountWordsPerLanguage.put(language, words);
    }//from   w w  w  .j a va 2s . c o m
    parser.close();
    reader.close();

}

From source file:Repackage.java

void writeFile(File f, StringBuffer chars) throws IOException {
    f.getParentFile().mkdirs();// w  w  w .j av a 2  s  .  c  om

    OutputStream out = new FileOutputStream(f);
    Writer w = new OutputStreamWriter(out);
    Reader r = new StringReader(chars.toString());

    copy(r, w);

    r.close();
    w.close();
    out.close();
}

From source file:it.greenvulcano.gvesb.utils.GVESBPropertyHandler.java

private String expandSQLProperties(String str, Map<String, Object> inProperties, Object object, Object extra)
        throws PropertiesHandlerException {
    PreparedStatement ps = null;/*from  ww w .j av  a  2 s  .c  o m*/
    ResultSet rs = null;
    String sqlStatement = null;
    Connection conn = null;
    String connName = "";
    boolean intConn = false;
    try {
        if (!PropertiesHandler.isExpanded(str)) {
            str = PropertiesHandler.expand(str, inProperties, object, extra);
        }
        int pIdx = str.indexOf("::");
        if (pIdx != -1) {
            connName = str.substring(0, pIdx);
            sqlStatement = str.substring(pIdx + 2);
            intConn = true;
        } else {
            sqlStatement = str;
        }
        if (intConn) {
            conn = JDBCConnectionBuilder.getConnection(connName);
        } else if ((extra != null) && (extra instanceof Connection)) {
            conn = (Connection) extra;
        } else {
            throw new PropertiesHandlerException(
                    "Error handling 'sql' metadata '" + str + "', Connection undefined.");
        }
        logger.debug("Executing SQL statement {" + sqlStatement + "} on connection [" + connName + "]");
        ps = conn.prepareStatement(sqlStatement);
        rs = ps.executeQuery();

        String paramValue = null;

        if (rs.next()) {
            ResultSetMetaData rsmeta = rs.getMetaData();
            if (rsmeta.getColumnType(1) == Types.CLOB) {
                Clob clob = rs.getClob(1);
                if (clob != null) {
                    Reader is = clob.getCharacterStream();
                    StringWriter strW = new StringWriter();

                    IOUtils.copy(is, strW);
                    is.close();
                    paramValue = strW.toString();
                }
            } else {
                paramValue = rs.getString(1);
            }
        }

        return (paramValue != null) ? paramValue.trim() : paramValue;
    } catch (Exception exc) {
        logger.warn("Error handling 'sql' metadata '" + sqlStatement + "'", exc);
        if (PropertiesHandler.isExceptionOnErrors()) {
            if (exc instanceof PropertiesHandlerException) {
                throw (PropertiesHandlerException) exc;
            }
            throw new PropertiesHandlerException("Error handling 'sql' metadata '" + str + "'", exc);
        }
        return "sql" + PROP_START + str + PROP_END;
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception exc) {
                // do nothing
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (Exception exc) {
                // do nothing
            }
        }
        if (intConn && (conn != null)) {
            try {
                JDBCConnectionBuilder.releaseConnection(connName, conn);
            } catch (Exception exc) {
                // do nothing
            }
        }
    }
}

From source file:TextFileHandler.java

public String readFile16(File f) throws IOException {
    StringBuilder sb = new StringBuilder();
    String line;/*  w  w  w.j a v  a  2s . com*/
    Reader in = null;
    try {
        in = new InputStreamReader(new FileInputStream(f), "UTF-16");
        BufferedReader reader = new BufferedReader(in);
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
    } finally {
        in.close();
    }
    return sb.toString();
}

From source file:de.uzk.hki.da.metadata.MetsMetadataStructure.java

public MetsMetadataStructure(Path workPath, File metadataFile, List<de.uzk.hki.da.model.Document> documents)
        throws FileNotFoundException, JDOMException, IOException {
    super(workPath, metadataFile, documents);

    metsFile = metadataFile;// w  w w. j a  va 2 s .co m
    currentDocuments = documents;

    SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder();
    FileInputStream fileInputStream = new FileInputStream(Path.makeFile(workPath, metsFile.getPath()));
    BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);
    Reader reader = new InputStreamReader(bomInputStream, "UTF-8");
    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");
    metsDoc = builder.build(is);
    metsParser = new MetsParser(metsDoc);

    fileElements = metsParser.getFileElementsFromMetsDoc(metsDoc);
    fileInputStream.close();

    bomInputStream.close();
    reader.close();
}

From source file:com.photon.phresco.util.Utility.java

/**
 * Closes inputsrteam./*from  w  w  w.  j a v a  2  s  .c  o m*/
 * @param inputStream
 */
public static void closeStream(Reader inputStream) {
    try {
        if (inputStream != null) {
            inputStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
        //FIXME: should be logged.
    }
}

From source file:com.icesoft.faces.renderkit.IncludeRenderer.java

public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
    if (context == null || component == null) {
        throw new NullPointerException("Null Faces context or component parameter");
    }//from  w  ww  .  java 2s .  c  o  m
    // suppress rendering if "rendered" property on the component is
    // false.
    if (!component.isRendered()) {
        return;
    }

    String page = (String) component.getAttributes().get("page");

    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    URI absoluteURI = null;
    try {
        absoluteURI = new URI(request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + request.getRequestURI());
        URL includedURL = absoluteURI.resolve(page).toURL();
        URLConnection includedConnection = includedURL.openConnection();
        includedConnection.setRequestProperty("Cookie",
                "JSESSIONID=" + ((HttpSession) context.getExternalContext().getSession(false)).getId());
        Reader contentsReader = new InputStreamReader(includedConnection.getInputStream());

        try {
            StringWriter includedContents = new StringWriter();
            char[] buf = new char[2000];
            int len = 0;
            while ((len = contentsReader.read(buf)) > -1) {
                includedContents.write(buf, 0, len);
            }

            ((UIOutput) component).setValue(includedContents.toString());
        } finally {
            contentsReader.close();
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
    }

    super.encodeBegin(context, component);
}

From source file:it.greenvulcano.gvesb.utils.GVESBPropertyHandler.java

private String expandSQLListProperties(String str, Map<String, Object> inProperties, Object object,
        Object extra) throws PropertiesHandlerException {
    PreparedStatement ps = null;//  www .j a va  2  s  .c  om
    ResultSet rs = null;
    String sqlStatement = null;
    Connection conn = null;
    String connName = "";
    String separator = ",";
    boolean intConn = false;
    try {
        if (!PropertiesHandler.isExpanded(str)) {
            str = PropertiesHandler.expand(str, inProperties, object, extra);
        }
        int pIdx = str.indexOf("::");
        if (pIdx != -1) {
            connName = str.substring(0, pIdx);
            sqlStatement = str.substring(pIdx + 2);
            int pIdx2 = str.indexOf("::", pIdx + 2);
            if (pIdx2 != -1) {
                separator = str.substring(pIdx + 2, pIdx2);
                sqlStatement = str.substring(pIdx2 + 2);
            }
            intConn = true;
        } else {
            sqlStatement = str;
        }
        if (intConn) {
            conn = JDBCConnectionBuilder.getConnection(connName);
        } else if ((extra != null) && (extra instanceof Connection)) {
            conn = (Connection) extra;
        } else {
            throw new PropertiesHandlerException(
                    "Error handling 'sqllist' metadata '" + str + "', Connection undefined.");
        }
        ps = conn.prepareStatement(sqlStatement);
        rs = ps.executeQuery();

        String paramValue = "";

        int type = rs.getMetaData().getColumnType(1);

        while (rs.next()) {
            if (type == Types.CLOB) {
                Clob clob = rs.getClob(1);
                if (clob != null) {
                    Reader is = clob.getCharacterStream();
                    StringWriter strW = new StringWriter();

                    IOUtils.copy(is, strW);
                    is.close();
                    paramValue += separator + strW.toString();
                } else {
                    paramValue += separator + "null";
                }
            } else {
                paramValue += separator + rs.getString(1);
            }
        }

        if (!paramValue.equals("")) {
            paramValue = paramValue.substring(separator.length());
        }

        return (paramValue != null) ? paramValue.trim() : paramValue;
    } catch (Exception exc) {
        logger.warn("Error handling 'sqllist' metadata '" + sqlStatement + "'", exc);
        if (PropertiesHandler.isExceptionOnErrors()) {
            if (exc instanceof PropertiesHandlerException) {
                throw (PropertiesHandlerException) exc;
            }
            throw new PropertiesHandlerException("Error handling 'sqllist' metadata '" + str + "'", exc);
        }
        return "sqllist" + PROP_START + str + PROP_END;
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception exc) {
                // do nothing
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (Exception exc) {
                // do nothing
            }
        }
        if (intConn && (conn != null)) {
            try {
                JDBCConnectionBuilder.releaseConnection(connName, conn);
            } catch (Exception exc) {
                // do nothing
            }
        }
    }
}

From source file:com.googlecode.fascinator.indexer.RuleManager.java

public void run(Reader in, Writer out) throws IOException {
    File tmpFile;//from w w  w. j  a  va 2 s . c om
    Reader tmpIn = in;
    Writer tmpOut = null;
    OutputStream tmpOutStream;
    cancelled = false;
    for (Rule rule : rules) {
        try {
            tmpFile = createTempFile("rule", ".xml");
            tmpOutStream = new FileOutputStream(tmpFile);
            tmpOut = new OutputStreamWriter(tmpOutStream, "UTF-8");
            rule.run(tmpIn, tmpOut);
            tmpOut.close();
            tmpOutStream.close();
            tmpIn.close();
            tmpIn = new InputStreamReader(new FileInputStream(tmpFile), "UTF-8");
        } catch (Exception e) {
            if (rule.isRequired()) {
                cancelled = true;
                log.error("Stopping since " + rule + " failed: ", e);
                break;
            } else {
                log.warn("Rule " + rule + " failed: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
    if (!cancelled) {
        IOUtils.copy(tmpIn, out);
    }
    tmpIn.close();
    out.close();
    cleanupTempFiles();
}

From source file:edu.washington.gs.skyline.model.quantification.QuantificationTest.java

private List<InputRecord> readInputRecords(String filename) throws Exception {
    List<InputRecord> list = new ArrayList<>();
    Reader reader = new InputStreamReader(QuantificationTest.class.getResourceAsStream(filename));
    try {/*from   www . j av a 2 s.com*/
        CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
        for (CSVRecord record : parser.getRecords()) {
            list.add(new InputRecord(record));
        }

    } finally {
        reader.close();
    }
    return list;
}