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:com.breadwallet.tools.threads.ImportPrivKeyTask.java

private static String callURL(String myURL) {
    //        System.out.println("Requested URL_EA:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {/*from w  w  w . ja  v a  2  s  .co m*/
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null)
            urlConn.setReadTimeout(60 * 1000);
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
            BufferedReader bufferedReader = new BufferedReader(in);

            int cp;
            while ((cp = bufferedReader.read()) != -1) {
                sb.append((char) cp);
            }
            bufferedReader.close();
        }
        assert in != null;
        in.close();
    } catch (Exception e) {
        return null;
    }

    return sb.toString();
}

From source file:org.openbaton.vnfm.utils.Utils.java

public static String getUserdataFromJar() {
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = {};//from   www  . j a v  a2s  . com
    StringBuilder script = new StringBuilder();
    try {
        resources = resolver.getResources("/scripts/*.sh");
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    for (Resource resource : resources) {
        InputStream in = null;
        InputStreamReader is = null;
        BufferedReader br = null;
        try {
            in = resource.getInputStream();
            is = new InputStreamReader(in);
            br = new BufferedReader(is);
            String line = br.readLine();
            while (line != null) {
                script.append(line).append("\n");
                line = br.readLine();
            }
            script.append("\n");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                br.close();
                is.close();
                in.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
    return script.toString();
}

From source file:dataflow.feed.api.Weather.java

/**
 * Method which builds the string of the URL to call
 * @param myURL the URL which must become a callURL
 * @return //from w  ww .j  a  v a  2s  .c  om
 */
public static String callURL(String myURL) {
    //System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null)
            urlConn.setReadTimeout(60 * 1000);
        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) {
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }

    return sb.toString();
}

From source file:Main.java

public static List<String> getTextToList(File file) {
    FileInputStream fileInputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;
    List<String> list = new ArrayList<String>();
    try {/*from w  w  w.j  a v  a2s  .c  o  m*/
        fileInputStream = new FileInputStream(file);
        inputStreamReader = new InputStreamReader(fileInputStream);
        bufferedReader = new BufferedReader(inputStreamReader);
        String text;
        while ((text = bufferedReader.readLine()) != null) {
            list.add(text);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return list;
}

From source file:Main.java

public static String generateString(InputStream stream, String encoding) {
    InputStreamReader reader = null;
    BufferedReader br = null;//  ww  w. j av  a2 s  .  c  o m
    try {
        if (encoding == null) {
            encoding = DEFAULT_ENCODE;
        }
        reader = new InputStreamReader(stream, encoding);

    } catch (UnsupportedEncodingException e1) {
        reader = new InputStreamReader(stream);
    }
    br = new BufferedReader(reader);
    StringBuffer sb = new StringBuffer();
    try {
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\r\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return sb.toString();
}

From source file:com.termmed.utils.FileHelper.java

/**
 * Count lines.//from  w w w.ja  va  2  s  .  co  m
 *
 * @param file the file
 * @param firstLineHeader the first line header
 * @return the int
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static int countLines(File file, boolean firstLineHeader) throws IOException {

    FileInputStream fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
    LineNumberReader reader = new LineNumberReader(isr);
    int cnt = 0;
    String lineRead = "";
    while ((lineRead = reader.readLine()) != null) {
    }

    cnt = reader.getLineNumber();
    reader.close();
    isr.close();
    fis.close();
    if (firstLineHeader) {
        return cnt - 1;
    } else {
        return cnt;
    }
}

From source file:och.util.FileUtil.java

public static String readFile(FileInputStream fis, String charset)
        throws UnsupportedEncodingException, IOException {
    InputStreamReader r = null;
    OutputStreamWriter w = null;/*from w w  w.  j  a  v  a  2s .c om*/

    try {
        r = new InputStreamReader(fis, charset);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        w = new OutputStreamWriter(out, charset);
        char[] buff = new char[1024 * 4];
        int i;
        while ((i = r.read(buff)) > 0) {
            w.write(buff, 0, i);
        }
        w.flush();
        return out.toString(charset);
    } finally {
        if (r != null)
            try {
                r.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        if (w != null)
            try {
                w.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
}

From source file:com.radicaldynamic.groupinform.activities.AccountFolderList.java

public static ArrayList<AccountFolder> loadFolderList() {
    if (Collect.Log.DEBUG)
        Log.d(Collect.LOGTAG, t + "loading folder cache");

    ArrayList<AccountFolder> folders = new ArrayList<AccountFolder>();

    if (!new File(Collect.getInstance().getCacheDir(), FileUtilsExtended.FOLDER_CACHE_FILE).exists()) {
        if (Collect.Log.WARN)
            Log.w(Collect.LOGTAG, t + "folder cache file cannot be read: aborting loadFolderList()");
        return folders;
    }//from ww w  .  ja v  a  2 s  .  c o m

    try {
        FileInputStream fis = new FileInputStream(
                new File(Collect.getInstance().getCacheDir(), FileUtilsExtended.FOLDER_CACHE_FILE));
        InputStreamReader reader = new InputStreamReader(fis);
        BufferedReader buffer = new BufferedReader(reader, 8192);
        StringBuilder sb = new StringBuilder();

        String cur;

        while ((cur = buffer.readLine()) != null) {
            sb.append(cur + "\n");
        }

        buffer.close();
        reader.close();
        fis.close();

        try {
            JSONArray jsonFolders = (JSONArray) new JSONTokener(sb.toString()).nextValue();

            for (int i = 0; i < jsonFolders.length(); i++) {
                JSONObject jsonFolder = jsonFolders.getJSONObject(i);

                AccountFolder folder = new AccountFolder(jsonFolder.getString("id"),
                        jsonFolder.getString("rev"), jsonFolder.getString("owner"),
                        jsonFolder.getString("name"), jsonFolder.getString("description"),
                        jsonFolder.getString("visibility"), jsonFolder.getBoolean("replication"));

                folders.add(folder);

                // Also update the account folder hash since this will be needed by BrowserActivity, among other things
                Collect.getInstance().getInformOnlineState().getAccountFolders().put(folder.getId(), folder);
            }
        } catch (JSONException e) {
            // Parse error (malformed result)
            if (Collect.Log.ERROR)
                Log.e(Collect.LOGTAG, t + "failed to parse JSON " + sb.toString());
            e.printStackTrace();
        }
    } catch (Exception e) {
        if (Collect.Log.ERROR)
            Log.e(Collect.LOGTAG, t + "unable to read folder cache: " + e.toString());
        e.printStackTrace();
    }

    return folders;
}

From source file:org.opencastproject.util.IoSupport.java

/**
 * Extracts the content from the given input stream. This method is intended to faciliate handling of processes that
 * have error, input and output streams.
 *
 * @param is//  w w  w  . j  a  va2s.c  o m
 *         the input stream
 * @return the stream content
 */
public static String getOutput(InputStream is) {
    InputStreamReader bis = new InputStreamReader(is);
    StringBuffer outputMsg = new StringBuffer();
    char[] chars = new char[1024];
    try {
        int len = 0;
        try {
            while ((len = bis.read(chars)) > 0) {
                outputMsg.append(chars, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } finally {
        if (bis != null)
            try {
                bis.close();
            } catch (IOException e) {
            }
    }
    return outputMsg.toString();
}

From source file:com.mpower.mintel.android.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 * /*www.j  a  va 2  s .c o  m*/
 * @param urlString
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient, String auth) {
    URI u = null;
    try {
        URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u, auth);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (entity != null && (statusCode != 200 || !entity.getContentType().getValue().toLowerCase()
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML))) {
            try {
                // don't really care about the stream...
                InputStream is = response.getEntity().getContent();
                // read to end of stream...
                final long count = 1024L;
                while (is.skip(count) == count)
                    ;
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (statusCode != 200) {
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase().contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
            } finally {
                if (isr != null) {
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        e.printStackTrace();
        String cause;
        if (e.getCause() != null) {
            cause = e.getCause().getMessage();
        } else {
            cause = e.getMessage();
        }
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}