List of usage examples for java.io Reader read
public int read(char cbuf[]) throws IOException
From source file:it.tidalwave.northernwind.frontend.ui.component.htmltemplate.TextHolder.java
private void loadTemplate() throws IOException { // FIXME: this should be done only once... Resource resource = null;//from ww w . ja v a2s . co m for (Class<?> clazz = getClass(); clazz.getSuperclass() != null; clazz = clazz.getSuperclass()) { final String templateName = clazz.getSimpleName() + ".txt"; resource = new ClassPathResource(templateName, clazz); if (resource.exists()) { break; } } try { if (resource == null) { throw new FileNotFoundException(); } final @Cleanup Reader r = new InputStreamReader(resource.getInputStream()); final CharBuffer charBuffer = CharBuffer.allocate((int) resource.contentLength()); final int length = r.read(charBuffer); r.close(); template = new String(charBuffer.array(), 0, length); } catch (FileNotFoundException e) // no specific template, fallback { log.warn("No template for {}, using default", getClass().getSimpleName()); template = "$content$\n"; } }
From source file:android.net.http.AbstractProxyTest.java
private String contentToString(HttpResponse response) throws IOException { StringWriter writer = new StringWriter(); char[] buffer = new char[1024]; Reader reader = new InputStreamReader(response.getEntity().getContent()); int length;//from w w w. j a v a2 s . c om while ((length = reader.read(buffer)) != -1) { writer.write(buffer, 0, length); } reader.close(); return writer.toString(); }
From source file:com.icesoft.faces.renderkit.IncludeRenderer.java
public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if (context == null || component == null) { throw new NullPointerException("Null Faces context or component parameter"); }/*from ww w . java 2 s. co m*/ // suppress rendering if "rendered" property on the component is // false. if (!component.isRendered()) { return; } String page = (String) component.getAttributes().get("page"); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); URI absoluteURI = null; try { absoluteURI = new URI(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI()); URL includedURL = absoluteURI.resolve(page).toURL(); URLConnection includedConnection = includedURL.openConnection(); includedConnection.setRequestProperty("Cookie", "JSESSIONID=" + ((HttpSession) context.getExternalContext().getSession(false)).getId()); Reader contentsReader = new InputStreamReader(includedConnection.getInputStream()); try { StringWriter includedContents = new StringWriter(); char[] buf = new char[2000]; int len = 0; while ((len = contentsReader.read(buf)) > -1) { includedContents.write(buf, 0, len); } ((UIOutput) component).setValue(includedContents.toString()); } finally { contentsReader.close(); } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(e.getMessage()); } } super.encodeBegin(context, component); }
From source file:gov.nih.nci.cabig.caaers.api.AdeersReportGeneratorTest.java
public void testImage() throws Exception { generator.setAdverseEventReportSerializer(new AdverseEventReportSerializer()); generator.setEvaluationService(evaluationService); String xmlFileName = "expedited_report_caaers_complete.xml"; InputStream is = AdeersReportGeneratorTest.class.getClassLoader().getResourceAsStream(xmlFileName); Writer writer = new StringWriter(); if (is != null) { char[] buffer = new char[1024]; try {//w w w . j a v a 2 s . c om Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } reader.close(); } finally { is.close(); } } String caAERSXML = writer.toString(); //System.out.println(caAERSXML); long now = System.currentTimeMillis(); String fileName = System.getProperty("java.io.tmpdir") + File.separator + "ae" + String.valueOf(now) + "report.png"; List<String> list = generator.generateImage(caAERSXML, fileName); }
From source file:com.claude.sharecam.util.CountryMaster.java
private CountryMaster(Context context) { mContext = context;// w w w .j a va 2 s. co m Resources res = mContext.getResources(); // builds country data from json InputStream is = res.openRawResource(R.raw.countries); Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } String jsonString = writer.toString(); JSONArray json = new JSONArray(); try { json = new JSONArray(jsonString); } catch (JSONException e) { e.printStackTrace(); } mCountryList = new String[json.length()]; for (int i = 0; i < json.length(); i++) { JSONObject node = json.optJSONObject(i); if (node != null) { Country country = new Country(); country.mCountryIso = node.optString("iso"); country.mDialPrefix = node.optString("tel"); country.mCountryName = getCountryName(node.optString("iso")); mCountries.add(country); mCountryList[i] = country.mCountryIso; } } }
From source file:com.stimulus.archiva.language.LanguageIdentifier.java
public String identify(Reader reader) throws IOException { StringBuffer out = new StringBuffer(); char[] buffer = new char[2048]; int len = 0;//from w ww.j a v a 2 s.c om while (((len = reader.read(buffer)) != -1) && ((analyzeLength == 0) || (out.length() < analyzeLength))) { if (analyzeLength != 0) { len = Math.min(len, analyzeLength - out.length()); } out.append(buffer, 0, len); } if (out.length() < MINIMUM_SAMPLE_LENGTH) { logger.debug("the sample is too small to reliably detect the language."); return null; } return identify(out); }
From source file:com.bah.applefox.main.plugins.fulltextindex.FTLoader.java
/** This method is used to get the page source from the given URL * @param url - the url from which to get the contents * @return - the page contents// w w w. j a va 2 s. c om */ private static String getPageContents(URL url) { String pageContents = ""; try { // Open the URL Connection URLConnection con = url.openConnection(); // Get the file path, and eliminate unreadable documents String filePath = url.toString(); // Reads content only if it is a valid format if (!(filePath.endsWith(".pdf") || filePath.endsWith(".doc") || filePath.endsWith(".jsp") || filePath.endsWith("rss") || filePath.endsWith(".css"))) { // Sets the connection timeout (in milliseconds) con.setConnectTimeout(1000); // Tries to match the character set of the Web Page String charset = "utf-8"; try { Matcher m = Pattern.compile("\\s+charset=([^\\s]+)\\s*").matcher(con.getContentType()); charset = m.matches() ? m.group(1) : "utf-8"; } catch (Exception e) { log.error("Page had no specified charset"); } // Reader derived from the URL Connection's input stream, with // the // given character set Reader r = new InputStreamReader(con.getInputStream(), charset); // String Buffer used to append each chunk of Web Page data StringBuffer buf = new StringBuffer(); // Tries to get an estimate of bytes available int BUFFER_SIZE = con.getInputStream().available(); // If BUFFER_SIZE is too small, increases the size if (BUFFER_SIZE <= 1000) { BUFFER_SIZE = 1000; } // Character array to hold each chunk of Web Page data char[] ch = new char[BUFFER_SIZE]; // Read the first chunk of Web Page data int len = r.read(ch); // Loops until end of the Web Page is reached while (len != -1) { // Appends the data chunk to the string buffer and gets the // next chunk buf.append(ch, 0, len); len = r.read(ch, 0, BUFFER_SIZE); } // Sets the pageContents to the newly created string pageContents = buf.toString(); } } catch (UnsupportedEncodingException e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } // Assume the body contents are blank if the character encoding is // not supported pageContents = ""; } catch (IOException e) { if (e.getMessage() != null) { log.error(e.getMessage()); } else { log.error(e.getStackTrace()); } // Assume the body contents are blank if the Web Page could not be // accessed pageContents = ""; } return pageContents; }
From source file:com.itude.mobile.android.util.DataUtil.java
/** * Get the byte array from an asset or file. * //ww w. ja va 2s.c o m * @param filename file name * @return byte array */ public byte[] readFromAssetOrFile(String filename) { if (_filenameToReader.containsKey(filename)) { // we have previously read this file, so use the correct reader directly. Reader readerForThisFile = _filenameToReader.get(filename); return readerForThisFile.read(filename); } else { // first time we try to read this file, try all readers TwinResult<byte[], Reader> result = _readerAll.read(filename); if (result._mainResult == null) { // in future we just dont try for this file anymore _filenameToReader.put(filename, _readerNone); // and only the first time we give a message String message = "DataUtil.readFromAssetOrFile: unable to read file or asset data from file with name " + filename; MBLog.i(TAG, message); } else { // in future immediately use the correct reader for this filename _filenameToReader.put(filename, result._secondResult); } return result._mainResult; } }
From source file:io.hypertrack.sendeta.model.CountryMaster.java
private CountryMaster(Context context) { mContext = context;/*from w w w .j a v a2 s .c o m*/ Resources res = mContext.getResources(); // builds country data from json InputStream is = res.openRawResource(R.raw.countries); Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } String jsonString = writer.toString(); JSONArray json = new JSONArray(); try { json = new JSONArray(jsonString); } catch (JSONException e) { e.printStackTrace(); } mCountryList = new String[json.length()]; for (int i = 0; i < json.length(); i++) { JSONObject node = json.optJSONObject(i); if (node != null) { Country country = new Country(); country.mCountryIso = node.optString("iso"); country.mDialPrefix = node.optString("tel"); country.mCountryName = getCountryName(node.optString("iso")); country.mImageId = getCountryFlagImageResource(node.optString("iso")); mCountries.add(country); mCountryList[i] = country.mCountryIso; } } }