List of usage examples for java.io Writer close
public abstract void close() throws IOException;
From source file:de.fenvariel.mavenfreemarker.FreemarkerPlugin.java
private void generate(Template template, File file, Map<String, Object> data, Map<String, Pattern> keepPatterns) throws MojoExecutionException { try {//from ww w . ja v a 2 s. c o m file.getParentFile().mkdirs(); includeKeepSections(file, keepPatterns, data); Writer writer = new FileWriter(file); try { template.process(data, writer); writer.flush(); System.out.println("Written " + file.getCanonicalPath()); } finally { writer.close(); } } catch (Exception ex) { throw new MojoExecutionException("error generating file: " + file.getAbsolutePath() + " from template " + template.getName() + " and source " + data, ex); } }
From source file:com.netxforge.oss2.config.LinkdConfigFactory.java
/** {@inheritDoc} */ protected synchronized void saveXml(String xml) throws IOException { if (xml != null) { long timestamp = System.currentTimeMillis(); final File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.LINKD_CONFIG_FILE_NAME); LogUtils.debugf(LinkdConfigFactory.class, "saveXml: saving config file at %d: %s", timestamp, cfgFile.getPath());/*from w ww. j a v a 2 s. c o m*/ final Writer fileWriter = new OutputStreamWriter(new FileOutputStream(cfgFile), "UTF-8"); fileWriter.write(xml); fileWriter.flush(); fileWriter.close(); LogUtils.debugf(LinkdConfigFactory.class, "saveXml: finished saving config file: %s", cfgFile.getPath()); } }
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());//from w w w . j av a 2 s . co 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:org.matsim.contrib.parking.parkingchoice.lib.GeneralLib.java
/** * Write out a list of Strings/*from ww w .j a v a 2s. c om*/ * * after each String in the list a "\n" is added. * * @param list * @param fileName */ public static void writeList(ArrayList<String> list, String fileName) { Writer writer = null; if (fileName.toLowerCase(Locale.ROOT).endsWith(".gz")) { writer = IOUtils.getBufferedWriter(fileName); } try { if (writer == null) { FileOutputStream fos = new FileOutputStream(fileName); writer = new OutputStreamWriter(fos); } char[] charArray = Lists.getCharsOfAllArrayItemsWithNewLineCharacterInbetween(list); writer.write(charArray); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.cloudera.sqoop.manager.CubridManagerExportTest.java
protected void createTestFile(String filename, String[] lines) throws IOException { File testdir = new File(getWarehouseDir()); if (!testdir.exists()) { testdir.mkdirs();/* w ww . java2 s . co m*/ } File file = new File(getWarehouseDir() + "/" + filename); Writer output = new BufferedWriter(new FileWriter(file)); for (String line : lines) { output.write(line); output.write("\n"); } output.close(); }
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/* www . j a v a 2s .co 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:edu.ku.brc.specify.extras.FishBaseInfoGetter.java
/** * Performs a "generic" HTTP request and fill member variable with results use * "getDigirResultsetStr" to get the results as a String * *///from w w w.j a v a2 s.co m public void getDOMDoc(final String url, final InfoType infoType) { dom = null; String fileName = tmpDir + File.separator + genus + "_" + species + "_" + infoType.toString() + ".xml"; //System.out.println(fileName); File file = new File(fileName); if (file.exists()) { try { dom = XMLHelper.readFileToDOM4J(file); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FishBaseInfoGetter.class, ex); ex.printStackTrace(); status = ErrorCode.Error; } } else { ////System.out.println("http://www.fishbase.org.ph/webservice/Species/SpeciesSummary.asp?Genus=Etheostoma&Species=ramseyi"); //System.out.println(url); byte[] bytes = super.doHTTPRequest(url); data = new String(bytes); int inx = data.indexOf("<?"); if (inx > -1) { data = data.substring(inx, data.length()); //System.out.println(data); try { Writer output = new BufferedWriter(new FileWriter(file)); output.write(data); output.flush(); output.close(); // Is is cheating and slow, but I will do it for now // XXX FIXME! dom = XMLHelper.readFileToDOM4J(file); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FishBaseInfoGetter.class, ex); ex.printStackTrace(); status = ErrorCode.Error; } } else { status = ErrorCode.Error; data = null; } } }
From source file:com.github.rwitzel.streamflyer.experimental.stateful.util.IdleModifierStatePerformanceTest.java
private void assertOverheadByWriter(String input, double expectedMaxSpentTime, double expectedMaxOverhead) throws Exception { // setup: create modifier and writer Writer originalWriter = new StringWriter(); ModifyingWriter writer = new ModifyingWriter(originalWriter, createIdleModifier()); // write the stream to an output stream long start = System.currentTimeMillis(); for (int index = 0; index < input.length(); index++) { writer.append(input.charAt(index)); }//from ww w . j a v a2 s. c o m writer.flush(); writer.close(); long end = System.currentTimeMillis(); originalWriter.toString(); Writer writer2 = new StringWriter(); // read the stream into an output stream long start2 = System.currentTimeMillis(); for (int index = 0; index < input.length(); index++) { writer2.append(input.charAt(index)); } writer2.flush(); writer2.close(); long end2 = System.currentTimeMillis(); long overhead = (end - start) - (end2 - start2); assertTime(end - start, expectedMaxSpentTime, "Time spent by ModifyingWriter:"); assertTime(overhead, expectedMaxOverhead, "Overhead by ModifyingWriter:"); }
From source file:org.springframework.data.couchbase.core.convert.translation.JacksonTranslationService.java
/** * Encode a {@link CouchbaseStorable} to a JSON string. * * @param source the source document to encode. * * @return the encoded JSON String.//from w w w . jav a2s . c o m */ @Override public final Object encode(final CouchbaseStorable source) { Writer writer = new StringWriter(); try { JsonGenerator generator = factory.createGenerator(writer); encodeRecursive(source, generator); generator.close(); writer.close(); } catch (IOException ex) { throw new RuntimeException("Could not encode JSON", ex); } return writer.toString(); }
From source file:com.tinspx.util.json.JSONParserTest.java
static void writeFormatted(String file, Object value) throws IOException { Writer caw = new BufferedWriter(new FileWriter(file), 1024 * 16); // caw.write("start json\n"); IndentingWriter.indentingBuilder().build().writeTo(caw, value); // caw.write("\nend of json\n"); caw.flush();/* ww w .j a va 2 s . c o m*/ caw.close(); }