List of usage examples for java.io InputStreamReader close
public void close() throws IOException
From source file:Main.java
/** * The method read a XML from URL, skips irrelevant chars and serves back the content as string. * @param inputStream//from ww w .j a v a 2s. co m * @return String : content of a file * @throws IOException */ public static String getURLToString(URL url) throws IOException { InputStreamReader inputStream = new InputStreamReader(url.openStream(), "ISO-8859-1"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { int i = inputStream.read(); while (i != -1) { if (i != TAB && i != NL && i != CR) byteArrayOutputStream.write(i); i = inputStream.read(); } String x = byteArrayOutputStream.toString("UTF-8"); return x; } catch (IOException e) { e.printStackTrace(); return ""; } finally { inputStream.close(); } }
From source file:Main.java
static boolean isTheUpdateForMe(File path) { JarFile jar;/* ww w . j ava2 s .c o m*/ try { jar = new JarFile(path); } catch (IOException e) { // TODO Auto-generated catch block return false; } ZipEntry entry = jar.getEntry("system/build.prop"); final String myDevice = "ro.product.device=" + Build.DEVICE; boolean finded = false; if (entry != null) { try { InputStreamReader bi = new InputStreamReader(jar.getInputStream(entry)); BufferedReader br = new BufferedReader(bi); String line; Pattern p = Pattern.compile(myDevice); do { line = br.readLine(); if (line == null) { break; } Matcher m = p.matcher(line); if (m.find()) { finded = true; break; } } while (true); bi.close(); } catch (IOException e) { // TODO Auto-generated catch block } } try { jar.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return finded; }
From source file:com.sitexa.android.community.utils.StringUtil.java
/** * InputStream???//from w w w . j a v a2 s .c o m * * @param is * @return */ public static String toConvertString(InputStream is) { StringBuffer res = new StringBuffer(); InputStreamReader isr = new InputStreamReader(is); BufferedReader read = new BufferedReader(isr); try { String line; line = read.readLine(); while (line != null) { res.append(line); line = read.readLine(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != isr) { isr.close(); isr.close(); } if (null != read) { read.close(); read = null; } if (null != is) { is.close(); is = null; } } catch (IOException e) { } } return res.toString(); }
From source file:com.radicaldynamic.groupinform.activities.AccountDeviceList.java
public static ArrayList<AccountDevice> loadDeviceList() { if (Collect.Log.DEBUG) Log.d(Collect.LOGTAG, t + "loading device cache"); ArrayList<AccountDevice> devices = new ArrayList<AccountDevice>(); if (!new File(Collect.getInstance().getCacheDir(), FileUtilsExtended.DEVICE_CACHE_FILE).exists()) { if (Collect.Log.WARN) Log.w(Collect.LOGTAG, t + "device cache file cannot be read: aborting loadDeviceList()"); return devices; }// w ww. j a v a2 s . c o m try { FileInputStream fis = new FileInputStream( new File(Collect.getInstance().getCacheDir(), FileUtilsExtended.DEVICE_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 { // int assignedSeats = 0; JSONArray jsonDevices = (JSONArray) new JSONTokener(sb.toString()).nextValue(); for (int i = 0; i < jsonDevices.length(); i++) { JSONObject jsonDevice = jsonDevices.getJSONObject(i); AccountDevice device = new AccountDevice(jsonDevice.getString("id"), jsonDevice.getString("rev"), jsonDevice.getString("alias"), jsonDevice.getString("email"), jsonDevice.getString("status")); // Optional information that will only be present if the user is also an account owner device.setLastCheckin(jsonDevice.optString("lastCheckin")); device.setPin(jsonDevice.optString("pin")); device.setRole(jsonDevice.optString("role")); // Update the lookup hash Collect.getInstance().getInformOnlineState().getAccountDevices().put(device.getId(), device); // Show a device so long as it hasn't been marked as removed if (!device.getStatus().equals("removed")) { devices.add(device); // assignedSeats++; } } // // Record the number of seats in this account that are assigned & allocated (not necessarily "active") // Collect.getInstance().getInformOnlineState().setAccountAssignedSeats(assignedSeats); } 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 device cache: " + e.toString()); e.printStackTrace(); } return devices; }
From source file:Main.java
/** * Read the text from a file/* ww w . jav a 2 s.c o m*/ * * @param file the file to read text from * @return the loaded text */ public static String loadTextFromFile(File file) { if (file.exists()) { InputStreamReader isr = null; FileInputStream fis = null; try { fis = new FileInputStream(file); isr = new InputStreamReader(fis, StandardCharsets.UTF_8); StringBuilder stringBuilder = new StringBuilder(); int i; while ((i = isr.read()) != -1) { stringBuilder.append((char) i); } return stringBuilder.toString(); } catch (IOException ignored) { } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } } } return ""; }
From source file:Main.java
public static String patchTemplateFile(InputStream src, Map replace) { InputStreamReader fr = new InputStreamReader(src); BufferedReader br = new BufferedReader(fr); StringBuffer result = new StringBuffer(); try {//from w w w .j a v a2 s. c om String line; while ((line = br.readLine()) != null) { Iterator iter; if (replace != null) { for (iter = replace.keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); line = line.replaceAll(key, (String) replace.get(key)); } } result.append(line + "\n"); } br.close(); fr.close(); } catch (IOException e) { return ""; } return result.toString(); }
From source file:Main.java
@SuppressWarnings("resource") public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) { Logd(TAG, "Starting post..."); String html = ""; Boolean cont = true;//from w w w. j a v a2s. co m URL url = null; try { url = new URL(targetUrl); } catch (MalformedURLException e) { Log.e(TAG, "Invalid url: " + targetUrl); cont = false; throw new IllegalArgumentException("Invalid url: " + targetUrl); } if (cont) { if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) { HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); } else { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } } }; // Install the all-trusting trust manager SSLContext sc; try { sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch (NoSuchAlgorithmException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } catch (KeyManagementException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } } Logd(TAG, "Filename: " + file); Logd(TAG, "URL: " + targetUrl); HttpURLConnection connection = null; DataOutputStream outputStream = null; String pathToOurFile = file; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024; try { connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header) //connection.setChunkedStreamingMode(1024); // Enable POST method connection.setRequestMethod("POST"); setBasicAuthentication(connection, url); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); //outputStream.writeBytes(twoHyphens + boundary + lineEnd); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\"" + lineEnd + lineEnd); outputStream.write(param.getValue().getBytes("UTF-8")); outputStream.writeBytes(lineEnd); } String connstr = null; if (!file.equals("")) { FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); Logd(TAG, "File length: " + bytesAvailable); try { while (bytesRead > 0) { try { outputStream.write(buffer, 0, bufferSize); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); fileInputStream.close(); } else if (data != null) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = data.length; Logd(TAG, "File length: " + bytesAvailable); try { outputStream.write(data, 0, data.length); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Logd(TAG, "Server Response Code " + serverResponseCode); Logd(TAG, "Server Response Message: " + serverResponseMessage); if (serverResponseCode == 200) { InputStreamReader in = new InputStreamReader(connection.getInputStream()); BufferedReader br = new BufferedReader(in); String decodedString; while ((decodedString = br.readLine()) != null) { html += decodedString; } in.close(); } outputStream.flush(); outputStream.close(); outputStream = null; } catch (Exception ex) { // Exception handling html = "Error: Unknown error"; Logd(TAG, "Send file Exception: " + ex.getMessage()); } } if (html.startsWith("success:")) Logd(TAG, "Server returned: success:HIDDEN"); else Logd(TAG, "Server returned: " + html); return html; }
From source file:com.andrious.btc.data.jsonUtils.java
public static String getJSONj(String url) { StringBuilder result = new StringBuilder(); InputStreamReader stream = HttpConn.urlStream(url); try {//from w w w .j a va 2 s . c o m BufferedReader reader = new BufferedReader(stream); String line; while ((line = reader.readLine()) != null) { result.append(line); } } catch (Exception ex) { result = new StringBuilder(); } finally { try { stream.close(); } catch (Exception ex) { } } return result.toString(); }
From source file:Main.java
/** * Load lines of strings from a file//from w w w . j ava 2s.c om * * @param path the path to the file * @param fileName the file name * @return an list of string lines */ public static List<String> loadFromFile(File path, String fileName) { ArrayList<String> arrayList = new ArrayList<>(); if (path.exists()) { File file = new File(path, fileName); BufferedReader bufferedReader = null; InputStreamReader isr = null; FileInputStream fis = null; try { fis = new FileInputStream(file); isr = new InputStreamReader(fis, StandardCharsets.UTF_8); bufferedReader = new BufferedReader(isr); String line; while ((line = bufferedReader.readLine()) != null) { arrayList.add(line); } return arrayList; } catch (IOException ignored) { } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } } } return null; }
From source file:nl.spellenclubeindhoven.dominionshuffle.DataReader.java
public static String readStringFromStream(InputStream inputStream) { InputStreamReader in = null; try {//from w ww. j ava 2 s . c o m in = new InputStreamReader(inputStream); StringBuilder builder = new StringBuilder(); char[] buffer = new char[1024]; int numread = 0; numread = in.read(buffer, 0, 1024); while (numread != -1) { builder.append(buffer, 0, numread); numread = in.read(buffer, 0, 1024); } return builder.toString(); } catch (IOException ignore) { } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } return ""; }