List of usage examples for java.io InputStreamReader close
public void close() throws IOException
From source file:com.mibr.android.intelligentreminder.INeedToo.java
public synchronized void writeLogTo(OutputStream out) throws FileNotFoundException, IOException { FileInputStream fis = null;// w ww . jav a 2 s. c om fis = getLogInputStream(); java.io.InputStreamReader isr = new InputStreamReader(fis); PrintWriter pw = new PrintWriter(out); char[] cc = new char[4096]; try { int cnt = isr.read(cc, 0, 4096); int c = 0; while (cnt > 0) { pw.write(cc, 0, cnt); cnt = isr.read(cc, 0, 4096); } } finally { try { isr.close(); } catch (Exception e) { } try { pw.flush(); } catch (Exception e2) { } try { pw.close(); } catch (Exception e2) { } } }
From source file:com.servoy.j2db.util.Utils.java
public static String getURLContent(URL url) { StringBuffer sb = new StringBuffer(); String charset = null;// w ww .j a va2 s. c om try { URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); final String type = connection.getContentType(); if (type != null) { final String[] parts = type.split(";"); for (int i = 1; i < parts.length && charset == null; i++) { final String t = parts[i].trim(); final int index = t.toLowerCase().indexOf("charset="); if (index != -1) charset = t.substring(index + 8); } } InputStreamReader isr = null; if (charset != null) isr = new InputStreamReader(is, charset); else isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); int read = 0; while ((read = br.read()) != -1) { sb.append((char) read); } br.close(); isr.close(); is.close(); } catch (Exception e) { Debug.error(e); } return sb.toString(); }
From source file:com.motorola.studio.android.utilities.TelnetFrameworkAndroid.java
/** * *///from w w w. j a va 2 s .c o m public String waitFor(String[] waitForArray) throws IOException { InputStreamReader responseReader = null; StringBuffer answerFromRemoteHost = new StringBuffer(); try { responseReader = new InputStreamReader(telnetClient.getInputStream()); boolean found = false; do { char readChar = 0; long currentTime = System.currentTimeMillis(); long timeoutTime = currentTime + timeout; while (readChar == 0) { if (responseReader == null) { // responseReader can only be set to null if method // releaseTelnetInputStreamReader() // has been called, which should happen if host becomes // unavailable. throw new IOException("Telnet host is unavailable; stopped waiting for answer."); } if (responseReader.ready()) { readChar = (char) responseReader.read(); } else { try { Thread.sleep(50); } catch (InterruptedException e) { // Do nothing } } currentTime = System.currentTimeMillis(); if ((!responseReader.ready()) && (currentTime > timeoutTime)) { throw new IOException("A timeout has occured when trying to read the telnet stream"); } } answerFromRemoteHost.append(readChar); for (String aWaitFor : waitForArray) { found = answerFromRemoteHost.toString().contains(aWaitFor); } } while (!found); } finally { if (responseReader != null) { responseReader.close(); } } return answerFromRemoteHost.toString(); }
From source file:com.taobao.diamond.client.impl.DefaultDiamondSubscriber.java
/** * Response/* w ww. j a va 2s . c o m*/ * * @param httpMethod * @return */ String getContent(HttpMethod httpMethod) { 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 contentBuilder.toString(); }
From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java
/** * // ww w. j a v a2 s .co m * * @param stream * * @param encoding * * @return * * @throws IOException * IO */ static String inputStreamToString(InputStream stream, String encoding) throws IOException { char buffer[] = new char[4096]; StringBuilder sb = new StringBuilder(); InputStreamReader isr = new InputStreamReader(stream, "utf-8"); // For // now, // assume // utf-8 // to // work // around // server // bug int nRead = 0; while ((nRead = isr.read(buffer)) >= 0) { sb.append(buffer, 0, nRead); } isr.close(); return sb.toString(); }
From source file:cn.leancloud.diamond.client.impl.DefaultDiamondSubscriber.java
/** * ?Response??/*from w w w . j ava 2 s .c om*/ * * @param httpMethod * @return */ String getContent(HttpMethod httpMethod) { 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 contentBuilder.toString(); }
From source file:com.southernstorm.tvguide.TvChannelCache.java
/** * Gets the last-modified date for a specific channel and date combination. * //from w w w. j ava 2s . com * @param channel the channel, or null for the main channel list file * @param date the date * @return the last-modified date, or null if the data is not in the cache */ public Calendar channelDataLastModified(TvChannel channel, Calendar date) { File file = dataFile(channel, date, ".cache"); if (file == null || !file.exists()) return null; try { FileInputStream input = new FileInputStream(file); try { InputStreamReader reader = new InputStreamReader(input, "utf-8"); try { String line; while ((line = readLine(reader)) != null) { if (line.startsWith("Last-Modified: ")) { String lastModified = line.substring(15); Date parsedDate = DateUtils.parseDate(lastModified); GregorianCalendar result = new GregorianCalendar(); result.setTime(parsedDate); return result; } } } catch (DateParseException e) { } finally { reader.close(); } } finally { input.close(); } } catch (IOException e) { } return null; }
From source file:org.apache.hadoop.util.SysInfoLinux.java
/** * Read /proc/cpuinfo, parse and calculate CPU information. *//*from w w w .j a v a2 s . c o m*/ private void readProcCpuInfoFile() { // This directory needs to be read only once if (readCpuInfoFile) { return; } HashSet<String> coreIdSet = new HashSet<>(); // Read "/proc/cpuinfo" file BufferedReader in; InputStreamReader fReader; try { fReader = new InputStreamReader(new FileInputStream(procfsCpuFile), Charset.forName("UTF-8")); in = new BufferedReader(fReader); } catch (FileNotFoundException f) { // shouldn't happen.... LOG.warn("Couldn't read " + procfsCpuFile + "; can't determine cpu info"); return; } Matcher mat; try { numProcessors = 0; numCores = 1; String currentPhysicalId = ""; String str = in.readLine(); while (str != null) { mat = PROCESSOR_FORMAT.matcher(str); if (mat.find()) { numProcessors++; } mat = FREQUENCY_FORMAT.matcher(str); if (mat.find()) { cpuFrequency = (long) (Double.parseDouble(mat.group(1)) * 1000); // kHz } mat = PHYSICAL_ID_FORMAT.matcher(str); if (mat.find()) { currentPhysicalId = str; } mat = CORE_ID_FORMAT.matcher(str); if (mat.find()) { coreIdSet.add(currentPhysicalId + " " + str); numCores = coreIdSet.size(); } 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); } } readCpuInfoFile = true; }
From source file:com.ibm.stocator.fs.swift.auth.PasswordScopeAccessProvider.java
/** * Authentication logic/*from w ww .java2 s . c om*/ * * @return Access JOSS access object * @throws IOException if failed to parse the response */ public Access passwordScopeAuth() throws IOException { InputStreamReader reader = null; BufferedReader bufReader = null; try { JSONObject user = new JSONObject(); user.put("id", mUserId); user.put("password", mPassword); JSONObject password = new JSONObject(); password.put("user", user); JSONArray methods = new JSONArray(); methods.add("password"); JSONObject identity = new JSONObject(); identity.put("methods", methods); identity.put("password", password); JSONObject project = new JSONObject(); project.put("id", mProjectId); JSONObject scope = new JSONObject(); scope.put("project", project); JSONObject auth = new JSONObject(); auth.put("identity", identity); auth.put("scope", scope); JSONObject requestBody = new JSONObject(); requestBody.put("auth", auth); HttpURLConnection connection = (HttpURLConnection) new URL(mAuthUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); OutputStream output = connection.getOutputStream(); output.write(requestBody.toString().getBytes()); int status = connection.getResponseCode(); if (status != 201) { return null; } reader = new InputStreamReader(connection.getInputStream()); bufReader = new BufferedReader(reader); String res = bufReader.readLine(); JSONParser parser = new JSONParser(); JSONObject jsonResponse = (JSONObject) parser.parse(res); String token = connection.getHeaderField("X-Subject-Token"); PasswordScopeAccess access = new PasswordScopeAccess(jsonResponse, token, mPrefferedRegion); bufReader.close(); reader.close(); connection.disconnect(); return access; } catch (Exception e) { if (bufReader != null) { bufReader.close(); } if (reader != null) { reader.close(); } throw new IOException(e); } }
From source file:org.alfresco.textgen.TextGenerator.java
public TextGenerator(String configPath) { ClassPathResource cpr = new ClassPathResource(configPath); if (!cpr.exists()) { throw new RuntimeException("No resource found: " + configPath); }//from w w w . jav a 2s. c om InputStream is = null; InputStreamReader r = null; BufferedReader br = null; try { int lineNumber = 0; is = cpr.getInputStream(); r = new InputStreamReader(is, "UTF-8"); br = new BufferedReader(r); String line; while ((line = br.readLine()) != null) { lineNumber++; if (lineNumber == 1) { // skip header continue; } String[] split = line.split("\t"); if (split.length != 7) { //System.out.println("Skipping "+lineNumber); continue; } String word = split[1].replaceAll("\\*", ""); String mode = split[3].replaceAll("\\*", ""); long frequency = Long.parseLong(split[4].replaceAll("#", "").trim()); // Single varient if (mode.equals(":")) { if (!ignore(word)) { wordGenerator.addWord(splitAlternates(word), frequency == 0 ? 1 : frequency); } } else { if (word.equals("@")) { // varient if (!ignore(mode)) { wordGenerator.addWord(splitAlternates(mode), frequency == 0 ? 1 : frequency); } } else { //System.out.println("Skipping totla and using varients for " + word + " @ " + lineNumber); } } } } catch (IOException e) { throw new RuntimeException("Failed to load resource " + configPath); } finally { if (br != null) { try { br.close(); } catch (Exception e) { } } if (r != null) { try { r.close(); } catch (Exception e) { } } if (is != null) { try { is.close(); } catch (Exception e) { } } } }