List of usage examples for java.io Reader close
public abstract void close() throws IOException;
From source file:gda.device.detector.mythen.data.MythenDataFileUtils.java
protected static double[][] getDataFromReaderUsingStreamTokenizer(Reader r, FileType type) throws IOException { try {//from ww w.ja v a 2 s . com List<double[]> data = new Vector<double[]>(); StreamTokenizer st = new StreamTokenizer(r); while (st.nextToken() != StreamTokenizer.TT_EOF) { double angle = st.nval; st.nextToken(); double count = st.nval; //st.nextToken(); if (type == FileType.PROCESSED) { st.nextToken(); double error = st.nval; data.add(new double[] { angle, count, error }); } else if (type == FileType.PROCESSED_WITH_CHANNELS) { st.nextToken(); double error = st.nval; double channel = st.nval; data.add(new double[] { angle, count, error, channel }); } else { data.add(new double[] { angle, count }); } } return data.toArray(new double[data.size()][]); } finally { try { r.close(); } catch (IOException e) { // ignore } } }
From source file:dk.dr.radio.data.JsonIndlaesning.java
sInputStreamSomStreng(InputStream is) throws IOException, UnsupportedEncodingException { // Det kan vre ndvendigt at hoppe over BOM mark - se http://android.forums.wordpress.org/topic/xml-pull-error?replies=2 //is.read(); is.read(); is.read(); // - dette virker kun hvis der ALTID er en BOM // Hop over BOM - hvis den er der! is = new BufferedInputStream(is); // bl.a. FileInputStream understtter ikke mark, s brug BufferedInputStream is.mark(1); // vi har faktisk kun brug for at sge n byte tilbage if (is.read() == 0xef) { is.read();/*from w ww .j a v a 2 s.co m*/ is.read(); } // Der var en BOM! Ls de sidste 2 byte else is.reset(); // Der var ingen BOM - hop tilbage til start final char[] buffer = new char[0x3000]; StringBuilder out = new StringBuilder(); Reader in = new InputStreamReader(is, "UTF-8"); int read; do { read = in.read(buffer, 0, buffer.length); if (read > 0) { out.append(buffer, 0, read); } } while (read >= 0); in.close(); return out.toString(); }
From source file:com.googlecode.fascinator.storage.filesystem.FileSystemPayload.java
/** * Read metadata from disk into memory if it exists * *//*w ww . j a v a2 s .co m*/ public void readExistingMetadata() { if (metaFile.exists()) { Properties props = new Properties(); Reader metaReader; try { metaReader = new FileReader(metaFile); props.load(metaReader); metaReader.close(); } catch (FileNotFoundException ex) { log.error("Failed reading metadata file", ex); } catch (IOException ex) { log.error("Failed accessing metadata file", ex); } setId(props.getProperty("id", getId())); String type = props.getProperty("payloadType", DEFAULT_PAYLOAD_TYPE.toString()); setType(PayloadType.valueOf(type)); setLabel(props.getProperty("label", getId())); String link = props.getProperty("linked", String.valueOf(isLinked())); setLinked(Boolean.parseBoolean(link)); if (isLinked()) { try { long fileSize = dataFile.length(); // Arbitrary test for length of link. We have observed // instances of real data being treated as a link. if (fileSize > 2000) { log.debug( "Linked file '{}' is unusually large. It is" + " most likely not really linked and is corrupt", dataFile.getAbsolutePath()); } else { String linkPath = FileUtils.readFileToString(dataFile); File linkFile = new File(linkPath); if (linkFile.exists()) { setContentType(MimeTypeUtil.getMimeType(linkFile)); } else { log.debug("Linked file '{}' no longer exists!", linkFile.getAbsolutePath()); } } } catch (IOException ioe) { log.warn("Failed to get linked file", ioe); } } else { setContentType(MimeTypeUtil.getMimeType(dataFile)); } } else { writeMetadata(); } }
From source file:com.streamsets.datacollector.util.TestConfiguration.java
@Test public void testRefsConfigs() throws IOException { File dir = new File("target", UUID.randomUUID().toString()); Assert.assertTrue(dir.mkdirs());// w w w .j av a 2 s. c o m Configuration.setFileRefsBaseDir(dir); Writer writer = new FileWriter(new File(dir, "hello.txt")); IOUtils.write("secret", writer); writer.close(); Configuration conf = new Configuration(); String home = System.getenv("HOME"); conf.set("a", "@hello.txt@"); conf.set("aa", "${file(\"hello.txt\")}"); conf.set("aaa", "${file('hello.txt')}"); conf.set("b", "$HOME$"); conf.set("bb", "${env(\"HOME\")}"); conf.set("bbb", "${env('HOME')}"); conf.set("x", "X"); Assert.assertEquals("secret", conf.get("a", null)); Assert.assertEquals("secret", conf.get("aa", null)); Assert.assertEquals("secret", conf.get("aaa", null)); Assert.assertEquals(home, conf.get("b", null)); Assert.assertEquals(home, conf.get("bb", null)); Assert.assertEquals(home, conf.get("bbb", null)); Assert.assertEquals("X", conf.get("x", null)); Configuration uconf = conf.getUnresolvedConfiguration(); Assert.assertEquals("@hello.txt@", uconf.get("a", null)); Assert.assertEquals("${file(\"hello.txt\")}", uconf.get("aa", null)); Assert.assertEquals("${file('hello.txt')}", uconf.get("aaa", null)); Assert.assertEquals("$HOME$", uconf.get("b", null)); Assert.assertEquals("${env(\"HOME\")}", uconf.get("bb", null)); Assert.assertEquals("${env('HOME')}", uconf.get("bbb", null)); Assert.assertEquals("X", uconf.get("x", null)); writer = new FileWriter(new File(dir, "config.properties")); conf.save(writer); writer.close(); conf = new Configuration(); Reader reader = new FileReader(new File(dir, "config.properties")); conf.load(reader); reader.close(); uconf = conf.getUnresolvedConfiguration(); Assert.assertEquals("@hello.txt@", uconf.get("a", null)); Assert.assertEquals("${file(\"hello.txt\")}", uconf.get("aa", null)); Assert.assertEquals("${file('hello.txt')}", uconf.get("aaa", null)); Assert.assertEquals("$HOME$", uconf.get("b", null)); Assert.assertEquals("${env(\"HOME\")}", uconf.get("bb", null)); Assert.assertEquals("${env('HOME')}", uconf.get("bbb", null)); Assert.assertEquals("X", uconf.get("x", null)); }
From source file:dk.ange.octave.exec.OctaveReaderCallable.java
@Override public Void call() { final Reader reader = new OctaveExecuteReader(processReader, spacer); try {// w w w . j ava 2 s .c o m readFunctor.doReads(reader); } catch (final IOException e) { final String message = "IOException from ReadFunctor"; log.debug(message, e); throw new OctaveIOException(message, e); } finally { try { reader.close(); } catch (final IOException e) { final String message = "IOException during close"; log.debug(message, e); throw new OctaveIOException(message, e); } } return null; }
From source file:cz.incad.kramerius.k5indexer.Commiter.java
/** * Reads data from the data reader and posts it to solr, writes the response * to output// w ww .j a v a 2 s . c o m */ private void postData(URL url, Reader data, String contentType, StringBuilder output) throws Exception { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(config.getInt("http.timeout", 10000)); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", contentType); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(data, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) { out.close(); } } InputStream in = urlc.getInputStream(); int status = urlc.getResponseCode(); StringBuilder errorStream = new StringBuilder(); try { if (status != HttpURLConnection.HTTP_OK) { errorStream.append("postData URL=").append(solrUrl).append(" HTTP response code=") .append(status).append(" "); throw new Exception("URL=" + solrUrl + " HTTP response code=" + status); } Reader reader = new InputStreamReader(in); pipeString(reader, output); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) { in.close(); } } InputStream es = urlc.getErrorStream(); if (es != null) { try { Reader reader = new InputStreamReader(es); pipeString(reader, errorStream); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (es != null) { es.close(); } } } if (errorStream.length() > 0) { throw new Exception("postData error: " + errorStream.toString()); } } catch (IOException e) { throw new Exception("Solr has throw an error. Check tomcat log. " + e); } finally { if (urlc != null) { urlc.disconnect(); } } }
From source file:net.ontopia.topicmaps.core.OccurrenceTest.java
public void testReader() throws Exception { // read file and store in object File filein = TestFileUtils.getTransferredTestInputFile("various", "clob.xml"); File fileout = TestFileUtils.getTestOutputFile("various", "clob.xml.out"); long inlen = filein.length(); Reader ri = new FileReader(filein); try {/*from w w w . ja v a 2 s. c om*/ occurrence.setReader(ri, inlen, DataTypes.TYPE_BINARY); } finally { try { ri.close(); } catch (Exception e) { e.printStackTrace(); } ; } assertTrue("Occurrence datatype is incorrect", Objects.equals(DataTypes.TYPE_BINARY, occurrence.getDataType())); // read and decode content Reader ro = occurrence.getReader(); try { Writer wo = new FileWriter(fileout); try { IOUtils.copy(ro, wo); } finally { wo.close(); } } finally { ro.close(); } assertTrue("Reader value is null", ro != null); try { ri = new FileReader(filein); ro = new FileReader(fileout); long outlen = occurrence.getLength(); try { assertTrue("Occurrence value put in is not the same as the one we get out.", IOUtils.contentEquals(ro, ri)); assertTrue("Occurrence value length is different", inlen == outlen); } finally { ri.close(); } } finally { ro.close(); } }
From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignProvider.java
private static void resourceInToOut(InputStream in, String sourceEncoding, OutputStream out, String targetEncoding) throws UnsupportedEncodingException, IOException { if (sourceEncoding != null && targetEncoding != null) { Reader inReader = new InputStreamReader(in, sourceEncoding); Writer outWriter = new OutputStreamWriter(out, targetEncoding); WGUtils.inToOut(inReader, outWriter, 4096); inReader.close(); outWriter.flush();/*from w w w . j ava 2 s . c o m*/ outWriter.close(); } else { WGUtils.inToOut(in, out, 4096); in.close(); out.flush(); out.close(); } }
From source file:org.eel.kitchen.jsonschema.GsonProviderTest.java
@DataProvider public Iterator<Object[]> getGson() throws IOException { final Set<Object[]> set = Sets.newHashSet(); final Gson gson = new Gson(); final InputStream in = getClass().getResourceAsStream("/provider/gson.json"); final Reader reader = new InputStreamReader(in); try {/*from w w w . j a v a 2 s . c om*/ // Unlike Jackson, Gson cannot read to its own format :/ final JsonElement[] array = gson.fromJson(reader, JsonElement[].class); for (final JsonElement element : array) set.add(new Object[] { element }); return set.iterator(); } finally { reader.close(); in.close(); } }
From source file:de.uzk.hki.da.metadata.XMPMetadataStructure.java
public XMPMetadataStructure(Path workPath, File metadataFile, List<de.uzk.hki.da.model.Document> documents) throws FileNotFoundException, JDOMException, IOException { super(workPath, metadataFile, documents); logger.debug("Instantiate new xmp metadata structure with metadata file " + metadataFile.getAbsolutePath() + " ... "); xmpFile = metadataFile;/*from w w w .j av a 2 s . co m*/ currentDocuments = documents; SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder(); FileInputStream fileInputStream = new FileInputStream(Path.makeFile(workPath, xmpFile.getPath())); BOMInputStream bomInputStream = new BOMInputStream(fileInputStream); Reader reader = new InputStreamReader(bomInputStream, "UTF-8"); InputSource is = new InputSource(reader); is.setEncoding("UTF-8"); rdfDoc = builder.build(is); descriptionElements = getXMPDescriptionElements(); fileInputStream.close(); bomInputStream.close(); reader.close(); }