Example usage for java.io InputStreamReader close

List of usage examples for java.io InputStreamReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:net.troja.eve.producersaid.utils.InvTypesReader.java

private void loadInvTypes() {
    invTypes = new HashMap<Integer, InvType>();
    try {/*  www .j  av  a  2s  .com*/
        final InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream("/" + dataFile));
        for (final CSVRecord record : CSVFormat.EXCEL.withHeader().parse(reader)) {
            if (!"0".equals(record.get(COLUMN_PUBLISHED))) {
                LOGGER.info("Found published: " + record.get(COLUMN_NAME));
            }
            final InvType invType = new InvType();
            invType.setId(Integer.parseInt(record.get(COLUMN_ID)));
            invType.setName(record.get(COLUMN_NAME));
            invType.setDescription(record.get(COLUMN_DESCRIPTION));
            invType.setGroupId(Integer.parseInt(record.get(COLUMN_GROUPID)));
            final String marketGroupId = record.get(COLUMN_MARKETGROUPID);
            if ((marketGroupId != null) && (marketGroupId.trim().length() > 0)) {
                invType.setMarketGroupId(Integer.parseInt(marketGroupId));
            }
            final String mass = record.get(COLUMN_MASS);
            if (!StringUtils.isEmpty(mass)) {
                invType.setMass(Double.parseDouble(mass));
            }
            final String volume = record.get(COLUMN_VOLUME);
            if (!StringUtils.isEmpty(volume)) {
                try {
                    invType.setVolume(Double.parseDouble(volume));
                } catch (final NumberFormatException e) {
                    LOGGER.error("Wrong number format, the csv is probably not converted with en_US locale!");
                }
            }
            invTypes.put(invType.getId(), invType);
        }
        reader.close();
    } catch (final IOException e) {
        LOGGER.error("Could not read CSV file of InvTypes", e);
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Loaded " + invTypes.size() + " invTypes");
    }
}

From source file:com.lenovo.tensorhusky.common.utils.LinuxResourceCalculatorPlugin.java

/**
 * Read /proc/meminfo, parse and compute memory information
 *
 * @param readAgain if false, read only on the first time
 *//*w w w.  j a  v  a2s.  co  m*/
private void readProcMemInfoFile(boolean readAgain) {

    if (readMemInfoFile && !readAgain) {
        return;
    }

    // Read "/proc/memInfo" file
    BufferedReader in = null;
    InputStreamReader fReader = null;
    try {
        fReader = new InputStreamReader(new FileInputStream(procfsMemFile), Charset.forName("UTF-8"));
        in = new BufferedReader(fReader);
    } catch (FileNotFoundException f) {
        // shouldn't happen....
        return;
    }

    Matcher mat = null;

    try {
        String str = in.readLine();
        while (str != null) {
            mat = PROCFS_MEMFILE_FORMAT.matcher(str);
            if (mat.find()) {
                if (mat.group(1).equals(MEMTOTAL_STRING)) {
                    ramSize = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(SWAPTOTAL_STRING)) {
                    swapSize = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(MEMFREE_STRING)) {
                    ramSizeFree = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(SWAPFREE_STRING)) {
                    swapSizeFree = Long.parseLong(mat.group(2));
                } else if (mat.group(1).equals(INACTIVE_STRING)) {
                    inactiveSize = Long.parseLong(mat.group(2));
                }
            }
            str = in.readLine();
        }
    } catch (IOException io) {
        LOG.warn("Error reading the stream " + io);
    } finally {
        // Close the streams
        try {
            fReader.close();
            try {
                in.close();
            } catch (IOException i) {
                LOG.warn("Error closing the stream " + in);
            }
        } catch (IOException i) {
            LOG.warn("Error closing the stream " + fReader);
        }
    }

    readMemInfoFile = true;
}

From source file:org.cryptsecure.Utility.java

/**
 * Get the content as string./*from   w  ww. j  ava  2 s .  co  m*/
 * 
 * @param response
 *            the response
 * @return the content as string
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static String getContentAsString(HttpResponse response) throws IOException {
    String returnString = "";
    HttpEntity httpEntity = response.getEntity();

    InputStream inputStream = httpEntity.getContent();
    InputStreamReader is = new InputStreamReader(inputStream);

    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(is);
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }

        returnString = writer.toString();

    }

    return returnString;
}

From source file:com.jflyfox.modules.filemanager.FileManager.java

private void loadLanguageFile() {

    // we load langCode var passed into URL if present
    // else, we use default configuration var
    if (language == null) {
        String lang = "";
        if (params.get("langCode") != null)
            lang = this.params.get("langCode");
        else/*from  w  w  w.j  a  v  a2s .c  om*/
            lang = getConfig("culture");
        BufferedReader br = null;
        InputStreamReader isr = null;
        String text;
        StringBuffer contents = new StringBuffer();
        try {
            isr = new InputStreamReader(
                    new FileInputStream(this.fileRoot + ROOT_PATH + "scripts/languages/" + lang + ".js"),
                    "UTF-8");
            br = new BufferedReader(isr);
            while ((text = br.readLine()) != null)
                contents.append(text);
            language = JSONObject.parseObject(contents.toString());
        } catch (Exception e) {
            this.error("Fatal error: Language file not found.");
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (Exception e2) {
            }
            try {
                if (isr != null)
                    isr.close();
            } catch (Exception e2) {
            }
        }
    }
}

From source file:com.util.httpRecargas.java

public List<Recarga> getRecargas(String idAccount, String page, String max, String startDate, String endDate) {

    //   System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/recharges/history/" + idAccount + ".json";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {//  w ww .  j  av a 2  s  . co  m
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(page, "UTF-8");
            data += "&" + URLEncoder.encode("max", "UTF-8") + "=" + URLEncoder.encode(max, "UTF-8");
            data += "&" + URLEncoder.encode("startDate", "UTF-8") + "=" + URLEncoder.encode(startDate, "UTF-8");
            data += "&" + URLEncoder.encode("endDate", "UTF-8") + "=" + URLEncoder.encode(endDate, "UTF-8");
            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println("DATOS ENVIADOS DEL SERVIDOR " + sb.toString());

    // System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    // JSONArray dataJson = new JSONArray();
    //  dataJson = objJason.getJSONArray("data");
    String jdata = objJason.optString("data");
    String mensaje = objJason.optString("message");
    System.out.println("\n MENSAJE DEL SERVIDOR " + mensaje);
    //   System.out.println(" el objeto jdata es " + jdata);
    objJason = new JSONObject(jdata);
    // System.out.println("objeto normal 1 " + objJason.toString());
    //
    jdata = objJason.optString("items");
    // System.out.println("\n\n el objeto jdata es " + jdata);
    JSONArray jsonArray = new JSONArray();
    Gson gson = new Gson();
    //objJason = gson.t
    jsonArray = objJason.getJSONArray("items");
    // System.out.println("\n\nEL ARRAY FINAL ES " + jsonArray.toString());
    /*
            List<String> list = new ArrayList<String>();
            for (int i = 0; i
        < jsonArray.length(); i++) {
    list.add(String.valueOf(i));
    list.add(jsonArray.getJSONObject(i).getString("created_date"));
    list.add(jsonArray.getJSONObject(i).getString("description"));
    list.add(String.valueOf(jsonArray.getJSONObject(i).getInt("credit")));
    list.add(jsonArray.getJSONObject(i).getString("before_balance"));
    list.add(jsonArray.getJSONObject(i).getString("after_balance"));
            }
            System.out.println("\n\nel array java contiene "+ list.toString());
    */
    List<Recarga> recargas = new ArrayList<Recarga>();

    for (int i = 0; i < jsonArray.length(); i++) {
        Recarga recarga = new Recarga();
        recarga.setNo(i);
        recarga.setFecha(jsonArray.getJSONObject(i).getString("created_date"));
        recarga.setDescripcion(jsonArray.getJSONObject(i).getString("description"));
        recarga.setMonto(String.valueOf(jsonArray.getJSONObject(i).getInt("credit")));
        recarga.setSaldoAnterior(jsonArray.getJSONObject(i).getString("before_balance"));
        recarga.setSaldoPosterior(jsonArray.getJSONObject(i).getString("after_balance"));

        recargas.add(recarga);
    }

    for (int i = 0; i < recargas.size(); i++) {
        System.out.print("\n\nNo" + recargas.get(i).getNo());
        System.out.print("\nFecna " + recargas.get(i).getFecha());
        System.out.print("\nDescripcion " + recargas.get(i).getDescripcion());
        System.out.print("\nMonto " + recargas.get(i).getMonto());
        System.out.print("\nSaldo Anterior " + recargas.get(i).getSaldoAnterior());
        System.out.print("\nSaldo Posterior" + recargas.get(i).getSaldoPosterior());

    }
    return recargas;

}

From source file:com.knowgate.dfs.FileSystem.java

/**
 * <p>Convert a text file from one character set to another</p>
 * The input file is overwritten.// w w  w.  ja va2s.c o  m
 * @param sFilePath File Path
 * @param sOldCharset Original file character set
 * @param sNewCharset New character set
 * @throws FileNotFoundException
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
public static void convert(String sFilePath, String sOldCharset, String sNewCharset)
        throws FileNotFoundException, IOException, UnsupportedEncodingException {

    if (DebugFile.trace) {
        DebugFile
                .writeln("Begin FileSystem.convert(" + sFilePath + "," + sOldCharset + "," + sNewCharset + ")");
        DebugFile.incIdent();
    }

    final int iBufferSize = 8192;
    int iReaded;
    char[] cBuffer = new char[iBufferSize];

    FileInputStream oFileStrm = new FileInputStream(sFilePath);

    BufferedInputStream oInStrm = new BufferedInputStream(oFileStrm);

    InputStreamReader oStrm = new InputStreamReader(oInStrm, sOldCharset);

    FileOutputStream oOutStrm = new FileOutputStream(sFilePath + ".tmp");

    while (true) {
        iReaded = oStrm.read(cBuffer, 0, iBufferSize);

        if (-1 == iReaded)
            break;

        oOutStrm.write(new String(cBuffer, 0, iReaded).getBytes(sNewCharset));
    }

    oOutStrm.close();

    oStrm.close();
    oInStrm.close();
    oFileStrm.close();

    File oOld = new File(sFilePath);
    oOld.delete();

    File oNew = new File(sFilePath + ".tmp");
    oNew.renameTo(oOld);

    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End FileSystem.convert()");
    }

}

From source file:org.activiti.bpmn.converter.BpmnXMLConverter.java

public BpmnModel convertToBpmnModel(InputStreamProvider inputStreamProvider, boolean validateSchema,
        boolean enableSafeBpmnXml, String encoding) {
    XMLInputFactory xif = XMLInputFactory.newInstance();

    if (xif.isPropertySupported(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)) {
        xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    }// w ww .ja  v  a 2 s  . c o m

    if (xif.isPropertySupported(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) {
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    }

    if (xif.isPropertySupported(XMLInputFactory.SUPPORT_DTD)) {
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    }

    InputStreamReader in = null;
    try {
        in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding);
        XMLStreamReader xtr = xif.createXMLStreamReader(in);

        try {
            if (validateSchema) {

                if (!enableSafeBpmnXml) {
                    validateModel(inputStreamProvider);
                } else {
                    validateModel(xtr);
                }

                // The input stream is closed after schema validation
                in = new InputStreamReader(inputStreamProvider.getInputStream(), encoding);
                xtr = xif.createXMLStreamReader(in);
            }

        } catch (Exception e) {
            throw new RuntimeException("Could not validate XML with BPMN 2.0 XSD", e);
        }

        // XML conversion
        return convertToBpmnModel(xtr);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("The bpmn 2.0 xml is not UTF8 encoded", e);
    } catch (XMLStreamException e) {
        throw new RuntimeException("Error while reading the BPMN 2.0 XML", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOGGER.debug("Problem closing BPMN input stream", e);
            }
        }
    }
}

From source file:com.taobao.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

/**
 * Response/*from ww  w.ja  v a2s . com*/
 * 
 * @param httpMethod
 * @return
 */
String getContent(HttpMethod httpMethod) throws UnsupportedEncodingException {
    StringBuilder contentBuilder = new StringBuilder();
    if (isZipContent(httpMethod)) {
        // 
        InputStream is = null;
        GZIPInputStream gzin = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            is = httpMethod.getResponseBodyAsStream();
            gzin = new GZIPInputStream(is);
            isr = new InputStreamReader(gzin, ((HttpMethodBase) httpMethod).getResponseCharSet()); // 
            br = new BufferedReader(isr);
            char[] buffer = new char[4096];
            int readlen = -1;
            while ((readlen = br.read(buffer, 0, 4096)) != -1) {
                contentBuilder.append(buffer, 0, readlen);
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            try {
                br.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                isr.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                gzin.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                is.close();
            } catch (Exception e1) {
                // ignore
            }
        }
    } else {
        // 
        String content = null;
        try {
            content = httpMethod.getResponseBodyAsString();
        } catch (Exception e) {
            log.error("", e);
        }
        if (null == content) {
            return null;
        }
        contentBuilder.append(content);
    }
    return StringEscapeUtils.unescapeHtml(contentBuilder.toString());
}

From source file:org.apache.cocoon.bean.CocoonBean.java

private void readChecksumFile() throws Exception {
    checksums = new HashMap();
    InputStream is = null;/*from w w w .  java 2 s  .co  m*/
    InputStreamReader isr = null;
    BufferedReader reader = null;
    try {
        Source checksumSource = sourceResolver.resolveURI(checksumsURI);
        is = checksumSource.getInputStream();
        isr = new InputStreamReader(is);
        reader = new BufferedReader(isr);
        String line;
        int lineNo = 0;
        while ((line = reader.readLine()) != null) {
            lineNo++;
            if (line.trim().startsWith("#") || line.trim().length() == 0) {
                continue;
            }
            if (line.indexOf("\t") == -1) {
                throw new ProcessingException("Missing tab at line " + lineNo + " of " + checksumsURI);
            }
            String filename = line.substring(0, line.indexOf("\t"));
            String checksum = line.substring(line.indexOf("\t") + 1);
            checksums.put(filename, checksum);
        }
        reader.close();
    } catch (SourceNotFoundException e) {
        // return leaving checksums map empty
    } finally {
        if (reader != null)
            reader.close();
        if (isr != null)
            isr.close();
        if (is != null)
            is.close();
    }
}

From source file:com.mobiperf.MeasurementScheduler.java

/**
 * Read in the results of tasks completed to date from a file, then clear the file.
 * //  w  ww.ja  va 2 s.  co  m
 * @return The results as a JSONArray, ready for sending to the server.
 */
private synchronized JSONArray readResultsFromFile() {

    JSONArray results = new JSONArray();
    try {
        Logger.i("Loading results from disk");
        FileInputStream inputstream = openFileInput("results");
        InputStreamReader streamreader = new InputStreamReader(inputstream);
        BufferedReader bufferedreader = new BufferedReader(streamreader);

        String line;
        while ((line = bufferedreader.readLine()) != null) {
            JSONObject jsonTask;
            try {
                jsonTask = new JSONObject(line);
                results.put(jsonTask);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        bufferedreader.close();
        streamreader.close();
        inputstream.close();

        // delete file once done, to avoid uploading results twice
        deleteFile("results");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return results;
}