List of usage examples for java.io Reader read
public int read(char cbuf[]) throws IOException
From source file:business.security.control.OwmClient.java
private JSONObject doQuery(String subUrl) throws JSONException, IOException { String responseBody = null;/*from w ww. j a v a 2s . c o m*/ HttpGet httpget = new HttpGet(this.baseOwmUrl + subUrl); if (this.owmAPPID != null) { httpget.addHeader(OwmClient.APPID_HEADER, this.owmAPPID); } HttpResponse response = this.httpClient.execute(httpget); InputStream contentStream = null; try { StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { throw new IOException(String.format("Unable to get a response from OWM server")); } int statusCode = statusLine.getStatusCode(); if (statusCode < 200 && statusCode >= 300) { throw new IOException( String.format("OWM server responded with status code %d: %s", statusCode, statusLine)); } /* Read the response content */ HttpEntity responseEntity = response.getEntity(); contentStream = responseEntity.getContent(); Reader isReader = new InputStreamReader(contentStream); int contentSize = (int) responseEntity.getContentLength(); if (contentSize < 0) { contentSize = 8 * 1024; } StringWriter strWriter = new StringWriter(contentSize); char[] buffer = new char[8 * 1024]; int n = 0; while ((n = isReader.read(buffer)) != -1) { strWriter.write(buffer, 0, n); } responseBody = strWriter.toString(); contentStream.close(); } catch (IOException e) { throw e; } catch (RuntimeException re) { httpget.abort(); throw re; } finally { if (contentStream != null) { contentStream.close(); } } return new JSONObject(responseBody); }
From source file:com.linuxbox.enkive.docsearch.indri.IndriDocSearchIndexService.java
private int indexDocumentAsString(Document doc, String identifier) throws DocStoreException, DocSearchException { try {/* w ww . j a va 2 s .co m*/ final StringBuilder docString = new StringBuilder(); final Reader input = contentAnalyzer.parseIntoText(doc); final char buffer[] = new char[4096]; int charsRead; while ((charsRead = input.read(buffer)) > 0) { docString.append(buffer, 0, charsRead); } final Map<String, String> metaData = new HashMap<String, String>(); metaData.put(NAME_FIELD, identifier); int documentId = indexEnvironmentManager.doAction(new IndexEnvironmentAction<Integer, Exception>() { @Override public Integer withIndexEnvironmentDo(IndexEnvironment indexEnvironment) throws Exception { return indexEnvironment.addString(docString.toString(), TEXT_FORMAT, metaData); } }); return documentId; } catch (DocStoreException e) { throw e; } catch (Exception e) { throw new DocSearchException("could not index \"" + identifier + "\"", e); } }
From source file:com.recomdata.transmart.data.export.util.FileWriterUtil.java
public String getClobAsString(Clob clob) { String strVal = ""; Reader reader = null; StringBuffer strBuf = null;//from w w w . jav a 2s .co m try { if (null != clob) { Long clobLength = (null != clob) ? clob.length() : 0; reader = clob.getCharacterStream(); if (null != clobLength && clobLength > 0 && null != reader) { //Here length of String is being rounded to 5000 * n, this is because the buffer size is 5000 //Sometimes the cloblength is less than 5000 * n char[] buffer = new char[clobLength.intValue()]; @SuppressWarnings("unused") int count = 0; strBuf = new StringBuffer(); while ((count = reader.read(buffer)) > 0) { strBuf.append(buffer); } strVal = strBuf.toString(); } } } catch (IOException e) { log.info(e.getMessage()); } catch (SQLException e2) { log.info("SQLException :: " + e2.getMessage()); } finally { try { if (null != reader) reader.close(); //Nullify the objects so they become ready for Garbage Collection reader = null; strBuf = null; clob = null; super.finalize(); } catch (IOException e) { log.info("Error closing Reader in getClobAsString"); } catch (Throwable e) { log.info("Error during super.finalize()"); } } return strVal; }
From source file:com.joliciel.frenchTreebank.search.XmlPatternSearchImpl.java
public void setXmlPatternFile(String xmlPatternFile) { try {/*from w w w . ja va 2 s. c o m*/ StringBuffer fileData = new StringBuffer(1000); Reader reader = new UnicodeReader(new FileInputStream(xmlPatternFile), "UTF-8"); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); xmlPattern = fileData.toString(); LOG.debug(xmlPattern); } catch (FileNotFoundException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } catch (IOException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } }
From source file:com.example.android.networkconnect.MainActivity.java
/** * Reads an InputStream and converts it to a String. * * @param stream InputStream containing HTML from targeted site. * @param len Length of string that this method returns. * @return String concatenated according to len parameter. * @throws java.io.IOException// www.j a v a 2s. co m * @throws java.io.UnsupportedEncodingException */ private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { // BufferedReader r = new BufferedReader(new InputStreamReader(stream)); //StringBuilder total = new StringBuilder(); //String line; //while ((line = r.readLine()) != null) { // total.append(line); //} //return total.toString(); Reader reader = null; //stream.available(); reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer); }
From source file:com.mocap.MocapFragment.java
private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { // BufferedReader r = new BufferedReader(new InputStreamReader(stream)); //StringBuilder total = new StringBuilder(); //String line; //while ((line = r.readLine()) != null) { // total.append(line); //}/* w ww .j a va2 s . c om*/ //return total.toString(); Reader reader = null; //stream.available(); reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer); }
From source file:de.interactive_instruments.ShapeChange.BasicTest.java
private String readFile(String fileName) throws Exception { InputStream stream = new FileInputStream(new File(fileName)); Writer writer = new StringWriter(); char[] buffer = new char[1024]; Reader reader = null; try {//from ww w .j a va 2s .c o m reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { if (reader != null) reader.close(); } return writer.toString(); }
From source file:org.jmxtrans.embedded.output.CopperEggWriter.java
public String convertStreamToString(InputStream is) throws IOException { ////from w w w .j av a 2 s. c om // To convert the InputStream to String we use the // Reader.read(char[] buffer) method. We iterate until the // Reader return -1 which means there's no more data to // read. We use the StringWriter class to produce the string. // if (is != null) { 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); } } finally { is.close(); } return writer.toString(); } else { return ""; } }
From source file:de.mpg.mpdl.inge.pubman.web.sword.SwordUtil.java
/** * This method takes a zip file and reads out the entries. * /*from w w w .ja va 2 s . co m*/ * @param in * @throws TechnicalException * @throws NamingException * @throws SWORDContentTypeException */ public PubItemVO readZipFile(InputStream in, AccountUserVO user) throws ItemInvalidException, ContentStreamNotFoundException, Exception { String item = null; List<FileVO> attachements = new ArrayList<FileVO>(); // List<String> attachementsNames = new ArrayList< String>(); PubItemVO pubItem = null; final int bufLength = 1024; char[] buffer = new char[bufLength]; int readReturn; int count = 0; try { ZipEntry zipentry; ZipInputStream zipinputstream = new ZipInputStream(in); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((zipentry = zipinputstream.getNextEntry()) != null) { count++; this.logger.debug("Processing zip entry file: " + zipentry.getName()); String name = URLDecoder.decode(zipentry.getName(), "UTF-8"); name = name.replaceAll("/", "_slsh_"); this.filenames.add(name); boolean metadata = false; // check if the file is a metadata file for (int i = 0; i < this.fileEndings.length; i++) { String ending = this.fileEndings[i]; if (name.endsWith(ending)) { metadata = true; // Retrieve the metadata StringWriter sw = new StringWriter(); Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8")); while ((readReturn = reader.read(buffer)) != -1) { sw.write(buffer, 0, readReturn); } item = new String(sw.toString()); this.depositXml = item; this.depositXmlFileName = name; pubItem = createItem(item, user); // if not escidoc format, add as component if (!this.currentDeposit.getFormatNamespace().equals(this.mdFormatEscidoc)) { attachements.add(convertToFileAndAdd(new ByteArrayInputStream(item.getBytes("UTF-8")), name, user, zipentry)); } } } if (!metadata) { attachements.add(convertToFileAndAdd(zipinputstream, name, user, zipentry)); } zipinputstream.closeEntry(); } zipinputstream.close(); // Now add the components to the Pub Item (if they do not exist. If they exist, use the // existing component metadata and just change the content) for (FileVO newFile : attachements) { boolean existing = false; for (FileVO existingFile : pubItem.getFiles()) { if (existingFile.getName().replaceAll("/", "_slsh_").equals(newFile.getName())) { // file already exists, replace content existingFile.setContent(newFile.getContent()); existingFile.getDefaultMetadata().setSize(newFile.getDefaultMetadata().getSize()); existing = true; } } if (!existing) { pubItem.getFiles().add(newFile); } } // If peer format, add additional copyright information to component. They are read from the // TEI metadata. if (this.currentDeposit.getFormatNamespace().equals(this.mdFormatPeerTEI)) { // Copyright information are imported from metadata file InitialContext initialContext = new InitialContext(); XmlTransformingBean xmlTransforming = new XmlTransformingBean(); Transformation transformer = new TransformationBean(); Format teiFormat = new Format("peer_tei", "application/xml", "UTF-8"); Format escidocComponentFormat = new Format("eSciDoc-publication-component", "application/xml", "UTF-8"); String fileXml = new String(transformer.transform(this.depositXml.getBytes(), teiFormat, escidocComponentFormat, "escidoc"), "UTF-8"); try { FileVO transformdedFileVO = xmlTransforming.transformToFileVO(fileXml); for (FileVO pubItemFile : pubItem.getFiles()) { pubItemFile.getDefaultMetadata() .setRights(transformdedFileVO.getDefaultMetadata().getRights()); pubItemFile.getDefaultMetadata() .setCopyrightDate(transformdedFileVO.getDefaultMetadata().getCopyrightDate()); } } catch (TechnicalException e) { this.logger.error("File Xml could not be transformed into FileVO. ", e); } } } catch (Exception e) { throw new RuntimeException(e); } if (count == 0) { this.logger.info("No zip file was provided."); this.depositServlet.setError("No zip file was provided."); throw new SWORDContentTypeException(); } // pubItem = this.processFiles(item, attachements, attachementsNames, user); return pubItem; }