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:markson.visuals.sitapp.settingActivity.java

public String ReadSettings(Context context) {

    FileInputStream fIn = null;/*ww w  . j a v a  2 s .  c  o  m*/

    InputStreamReader isr = null;

    char[] inputBuffer = new char[255];

    String data = null;

    try {

        fIn = openFileInput("settings.dat");

        isr = new InputStreamReader(fIn);

        isr.read(inputBuffer);

        data = new String(inputBuffer);

        //Toast.makeText(context, "Classes Loaded",Toast.LENGTH_SHORT).show();

    }

    catch (Exception e) {

        e.printStackTrace();

        Toast.makeText(context, "Settings not read", Toast.LENGTH_SHORT).show();

    }

    finally {

        try {

            isr.close();

            fIn.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    return data;

}

From source file:com.bstek.dorado.view.config.attachment.JavaScriptParser.java

public JavaScriptContent parse(Resource resource, String charset, boolean asControllerInDefault)
        throws IOException {
    InputStream in = resource.getInputStream();
    try {/* ww  w  .j a va  2  s.c  om*/
        InputStreamReader reader;
        if (StringUtils.isNotEmpty(charset)) {
            reader = new InputStreamReader(in, charset);
        } else {
            reader = new InputStreamReader(in);
        }
        BufferedReader br = new BufferedReader(reader);

        StringBuffer source = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            source.append(line).append('\n');
        }
        br.close();
        reader.close();

        JavaScriptContext context = new JavaScriptContext();
        if (asControllerInDefault) {
            context.setIsController(true);
        }
        return parse(source, context);
    } finally {
        in.close();
    }
}

From source file:com.farmerbb.notepad.activity.MainActivity.java

@Override
public String loadNoteTitle(String filename) throws IOException {
    // Open the file on disk
    FileInputStream input = openFileInput(filename);
    InputStreamReader reader = new InputStreamReader(input);
    BufferedReader buffer = new BufferedReader(reader);

    // Load the file
    String line = buffer.readLine();

    // Close file on disk
    reader.close();

    return (line);
}

From source file:com.ontotext.s4.client.HttpClient.java

/**
* Read an error response from the given connection and throw a
* suitable {@link HttpClientException}. This method always throws an
* exception, it will never return normally.
*///from   w  ww  . java2  s  .  c o m
private void readError(HttpURLConnection connection) throws HttpClientException {
    InputStream stream;
    try {
        String encoding = connection.getContentEncoding();
        if ("gzip".equalsIgnoreCase(encoding)) {
            stream = new GZIPInputStream(connection.getInputStream());
        } else {
            stream = connection.getInputStream();
        }

        InputStreamReader reader = new InputStreamReader(stream, "UTF-8");

        try {
            JsonNode errorNode = null;
            if (connection.getContentType().contains("json")) {
                errorNode = MAPPER.readTree(stream);
            } else if (connection.getContentType().contains("xml")) {
                errorNode = XML_MAPPER.readTree(stream);
            }

            throw new HttpClientException("Server returned response code " + connection.getResponseCode(),
                    errorNode);

        } finally {
            reader.close();
        }
    } catch (HttpClientException e2) {
        throw e2;
    } catch (Exception e2) {
        throw new HttpClientException("Error communicating with server", e2);
    }
}

From source file:org.apache.tapestry.engine.DefaultTemplateSource.java

/**
 *  Reads a Stream into memory as an array of characters.
 *
 **///from   w  w w .ja  v a  2 s .c o  m

private char[] readTemplateStream(InputStream stream, String encoding) throws IOException {
    char[] charBuffer = new char[BUFFER_SIZE];
    StringBuffer buffer = new StringBuffer();

    InputStreamReader reader;
    if (encoding != null)
        reader = new InputStreamReader(new BufferedInputStream(stream), encoding);
    else
        reader = new InputStreamReader(new BufferedInputStream(stream));

    try {
        while (true) {
            int charsRead = reader.read(charBuffer, 0, BUFFER_SIZE);

            if (charsRead <= 0)
                break;

            buffer.append(charBuffer, 0, charsRead);
        }
    } finally {
        reader.close();
    }

    // OK, now reuse the charBuffer variable to
    // produce the final result.

    int length = buffer.length();

    charBuffer = new char[length];

    // Copy the character out of the StringBuffer and into the
    // array.

    buffer.getChars(0, length, charBuffer, 0);

    return charBuffer;
}

From source file:de.alosdev.android.customerschoice.CustomersChoice.java

/**
 * loading the file content into a String and then parsing it.
 *
 * @param inputStream/*from   w ww  .j  a va  2 s .  c  o m*/
 * @throws FileNotFoundException
 * @throws IOException
 */
private void readFromInputStream(InputStream inputStream) throws FileNotFoundException, IOException {
    BufferedReader reader = null;
    InputStreamReader is = null;
    try {
        is = new InputStreamReader(inputStream);
        reader = new BufferedReader(is, 8192);

        String line = null;

        final StringBuilder result = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        parseStringVariants(result.toString());
    } finally {
        if (null != is) {
            is.close();
        }
        if (null != reader) {
            reader.close();
        }
    }
}

From source file:com.algolia.search.saas.APIClient.java

private JSONObject _requestByHost(HttpRequestBase req, String host, String url, String json,
        HashMap<String, String> errors) throws AlgoliaException {
    req.reset();/*w w w. ja v a  2s .  c o  m*/

    // set URL
    try {
        req.setURI(new URI("https://" + host + url));
    } catch (URISyntaxException e) {
        // never reached
        throw new IllegalStateException(e);
    }

    // set auth headers
    req.setHeader("X-Algolia-Application-Id", this.applicationID);
    if (forwardAdminAPIKey == null) {
        req.setHeader("X-Algolia-API-Key", this.apiKey);
    } else {
        req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey);
        req.setHeader("X-Forwarded-For", this.forwardEndUserIP);
        req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey);
    }
    for (Entry<String, String> entry : headers.entrySet()) {
        req.setHeader(entry.getKey(), entry.getValue());
    }

    // set user agent
    req.setHeader("User-Agent", "Algolia for Java " + version);

    // set JSON entity
    if (json != null) {
        if (!(req instanceof HttpEntityEnclosingRequestBase)) {
            throw new IllegalArgumentException("Method " + req.getMethod() + " cannot enclose entity");
        }
        req.setHeader("Content-type", "application/json");
        try {
            StringEntity se = new StringEntity(json, "UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            ((HttpEntityEnclosingRequestBase) req).setEntity(se);
        } catch (UnsupportedEncodingException e) {
            throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$
        }
    }

    RequestConfig config = RequestConfig.custom().setSocketTimeout(httpSocketTimeoutMS)
            .setConnectTimeout(httpConnectTimeoutMS).setConnectionRequestTimeout(httpConnectTimeoutMS).build();
    req.setConfig(config);

    HttpResponse response;
    try {
        response = httpClient.execute(req);
    } catch (IOException e) {
        // on error continue on the next host
        errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage()));
        return null;
    }
    try {
        int code = response.getStatusLine().getStatusCode();
        if (code / 100 == 4) {
            String message = "";
            try {
                message = EntityUtils.toString(response.getEntity());
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (code == 400) {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Bad request");
            } else if (code == 403) {
                throw new AlgoliaException(code,
                        message.length() > 0 ? message : "Invalid Application-ID or API-Key");
            } else if (code == 404) {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Resource does not exist");
            } else {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Error");
            }
        }
        if (code / 100 != 2) {
            try {
                errors.put(host, EntityUtils.toString(response.getEntity()));
            } catch (IOException e) {
                errors.put(host, String.valueOf(code));
            }
            // KO, continue
            return null;
        }
        try {
            InputStream istream = response.getEntity().getContent();
            InputStreamReader is = new InputStreamReader(istream, "UTF-8");
            JSONTokener tokener = new JSONTokener(is);
            JSONObject res = new JSONObject(tokener);
            is.close();
            return res;
        } catch (IOException e) {
            return null;
        } catch (JSONException e) {
            throw new AlgoliaException("JSON decode error:" + e.getMessage());
        }
    } finally {
        req.releaseConnection();
    }
}

From source file:com.v4creations.tmd.system.api.JSONConverter.java

@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
    String charset = "UTF-8";
    if (body.mimeType() != null) {
        charset = MimeUtil.parseCharset(body.mimeType());
    }/* ww w  .j  ava2 s .c  o  m*/
    InputStreamReader isr = null;
    try {
        isr = new InputStreamReader(body.in(), charset);
        BufferedReader bufferedReader = new BufferedReader(isr);
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        String json = stringBuilder.toString();
        if (json.startsWith("{"))
            return new JSONObject(json);
        else
            return new JSONArray(json);
    } catch (IOException e) {
        throw new ConversionException(e);
    } catch (JsonParseException e) {
        throw new ConversionException(e);
    } catch (JSONException e) {
        throw new ConversionException(e);
    } finally {
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:net.alastairwyse.oraclepermissiongenerator.datainterfacelayer.RestRemoteDataModelProxy.java

/**
 * Converts an HttpResponse object to a string.
 * @param   httpResponse  The HttpResponse to convert.
 * @return                The HttpResponse converted to a string.
 * @throws  IOException   if an error occurs when converting the HTTP response to a string.
 *//*from  w w w  .  j  a va  2s  .  c  o  m*/
private String ConvertHttpResponseToString(HttpResponse httpResponse) throws IOException {
    char[] characterBuffer = new char[(int) httpResponse.getEntity().getContentLength()];
    // TODO: If project compliance is changed to Java 1.7 or higher, change below to try with resources statement  
    InputStreamReader inputStreamReader = new InputStreamReader(httpResponse.getEntity().getContent());
    try {
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader,
                (int) httpResponse.getEntity().getContentLength());
        try {
            bufferedReader.read(characterBuffer, 0, (int) httpResponse.getEntity().getContentLength());
        } finally {
            bufferedReader.close();
        }
    } finally {
        inputStreamReader.close();
    }

    return new String(characterBuffer);
}

From source file:com.bstek.dorado.core.store.SqlBaseStoreSupport.java

protected void runInitScriptFile(Connection conn, Resource initScriptFile) throws Exception {
    InputStream is = initScriptFile.getInputStream();
    try {//from  w w w  .j  ava2 s  .  com
        InputStreamReader isr = new InputStreamReader(is,
                StringUtils.defaultIfEmpty(scriptFileCharset, Constants.DEFAULT_CHARSET));
        BufferedReader br = new BufferedReader(isr);

        StringBuffer scripts = new StringBuffer();
        String line = br.readLine();
        while (line != null) {
            scripts.append(line).append('\n');
            line = br.readLine();
        }

        if (scripts.length() > 0) {
            CallableStatement prepareCall = conn.prepareCall(scripts.toString());
            try {
                prepareCall.execute();
            } finally {
                prepareCall.close();
            }
        }

        br.close();
        isr.close();
    } finally {
        is.close();
    }
}