Java Code Examples for java.io.Writer#close()
The following examples show how to use
java.io.Writer#close() .
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: twill File: TrackerService.java License: Apache License 2.0 | 6 votes |
private void writeResourceReport(Channel channel) { ByteBuf content = Unpooled.buffer(); Writer writer = new OutputStreamWriter(new ByteBufOutputStream(content), CharsetUtil.UTF_8); try { reportAdapter.toJson(resourceReport.get(), writer); writer.close(); } catch (IOException e) { LOG.error("error writing resource report", e); writeAndClose(channel, new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.copiedBuffer(e.getMessage(), StandardCharsets.UTF_8))); return; } FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content); HttpUtil.setContentLength(response, content.readableBytes()); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8"); channel.writeAndFlush(response); }
Example 2
Source Project: wallpaper File: StreamUtils.java License: GNU General Public License v2.0 | 6 votes |
public static String convertStreamToString(InputStream inputStream) throws IOException { if (inputStream != null) { InputStreamReader insr = new InputStreamReader(inputStream); Writer writer = new StringWriter(); int length = 1024; char[] buffer = new char[length]; try { Reader reader = new BufferedReader(insr, length); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } reader.close(); } finally { writer.close(); insr.close(); } return writer.toString(); } else { return null; } }
Example 3
Source Project: hottub File: T6759996.java License: GNU General Public License v2.0 | 6 votes |
void write(File to, String body) throws IOException { System.err.println("write " + to); File toDir = to.getParentFile(); if (toDir != null) { boolean ok = toDir.mkdirs(); if (!ok) { throw new Error("could not create directory " + toDir); } } Writer out = new FileWriter(to); try { out.write(body); if (!body.endsWith("\n")) out.write("\n"); } finally { out.close(); } }
Example 4
Source Project: secure-data-service File: SelectorDoc.java License: Apache License 2.0 | 6 votes |
protected boolean writeSelectorDocumentationToFile(String documentationString, Writer output) { if (documentationString == null) { return false; } try { output.write(documentationString); output.flush(); output.close(); } catch (IOException e) { LOG.warn(e.getMessage()); return false; } return true; }
Example 5
Source Project: ontopia File: TestTMRAPOperation.java License: Apache License 2.0 | 6 votes |
protected void verifyCanonical(String filename) throws IOException { // Figure out base URL String root = TestFileUtils.getTestdataOutputDirectory() + File.separator + testdataDirectory + File.separator; LocatorIF base = new URILocator(new File(root)); // Import the TM String xtmfile = root + "out" + File.separator + filename; Reader reader = new FileReader(xtmfile); XTMTopicMapReader xtmReader = new XTMTopicMapReader(reader, base); xtmReader.setExternalReferenceHandler( new NullResolvingExternalReferenceHandler()); TopicMapIF importedTM = xtmReader.read(); reader.close(); TMRAPTestCase.filterUnifyingTopics(importedTM); // Canonicalize the reimported TM Writer out = new FileWriter(xtmfile + ".cxtm"); new CanonicalXTMWriter(out).write(importedTM); out.close(); // Compare results String baseline = TestFileUtils.getTestInputFile(testdataDirectory, "baseline", filename); Assert.assertTrue(filename + " did not match baseline", TestFileUtils.compareFileToResource(xtmfile + ".cxtm", baseline)); }
Example 6
Source Project: aliyun-maxcompute-data-collectors File: OracleCallExportTest.java License: Apache License 2.0 | 6 votes |
public void testExportUsingProcedure() throws IOException, SQLException { String[] lines = { "0,textfield0,2002-12-29 08:40:00,3300", "1,textfield1,2007-06-04 13:15:10,4400", }; new File(getWarehouseDir()).mkdirs(); File file = new File(getWarehouseDir() + "/part-00000"); Writer output = new BufferedWriter(new FileWriter(file)); for (String line : lines) { output.write(line); output.write("\n"); } output.close(); runExport(getArgv()); verifyExport(2, getConnection()); }
Example 7
Source Project: mobi File: OntologyRest.java License: GNU Affero General Public License v3.0 | 5 votes |
/** * Streams the ontology associated with the requested record ID to an OutputStream. * * @param context the context of the request * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless * String begins with "_:". * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless * String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the * master Branch. * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless * String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head * Commit. The provided commitId must be on the Branch identified by the provided branchId; * otherwise, nothing will be returned. * @param rdfFormat the desired RDF return format. NOTE: Optional param - defaults to "jsonld". * @param fileName the file name for the ontology file * @return the ontology associated with requested record ID to download. */ @GET @Path("{recordId}") @Produces({MediaType.APPLICATION_OCTET_STREAM, "text/*", "application/*"}) @RolesAllowed("user") @ApiOperation("Streams the associated ontology to an OutputStream.") @ResourceId(type = ValueType.PATH, value = "recordId") public Response downloadOntologyFile(@Context ContainerRequestContext context, @PathParam("recordId") String recordIdStr, @QueryParam("branchId") String branchIdStr, @QueryParam("commitId") String commitIdStr, @DefaultValue("jsonld") @QueryParam("rdfFormat") String rdfFormat, @DefaultValue("ontology") @QueryParam("fileName") String fileName) { try { Ontology ontology = getOntology(context, recordIdStr, branchIdStr, commitIdStr, true).orElseThrow(() -> ErrorUtils.sendError("The ontology could not be found.", Response.Status.BAD_REQUEST)); StreamingOutput stream = os -> { Writer writer = new BufferedWriter(new OutputStreamWriter(os)); writer.write(getOntologyAsRdf(ontology, rdfFormat, false)); writer.flush(); writer.close(); }; return Response.ok(stream).header("Content-Disposition", "attachment;filename=" + fileName + "." + getRDFFormatFileExtension(rdfFormat)).header("Content-Type", getRDFFormatMimeType(rdfFormat)).build(); } catch (MobiException e) { throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR); } }
Example 8
Source Project: gemfirexd-oss File: LobStreamsTest.java License: Apache License 2.0 | 5 votes |
/** * Tests the ClobWriter.write(String str) method **/ public void testClobCharacterWrite1ParamString() throws Exception { PreparedStatement stmt3 = prepareStatement( "SELECT c FROM testBlobX1 WHERE a = 1"); ResultSet rs3 = stmt3.executeQuery(); rs3.next(); Clob clob = rs3.getClob(1); assertTrue("FAIL -- clob is NULL", clob != null); Writer clobWriter = clob.setCharacterStream(1L); clobWriter.write(unicodeTestString); clobWriter.close(); PreparedStatement stmt4 = prepareStatement( "UPDATE testBlobX1 SET c = ? WHERE a = 1"); stmt4.setClob(1, clob); stmt4.executeUpdate(); stmt4.close(); rs3.close(); rs3 = stmt3.executeQuery(); assertTrue("FAIL -- clob not found", rs3.next()); long new_length = rs3.getClob(1).length(); assertEquals("FAIL -- wrong clob length", unicodeTestString.length(), new_length); // Check contents ... Reader lStream = rs3.getClob(1).getCharacterStream(); assertTrue("FAIL - Clob and buffer contents do not match", compareClobReader2CharArray( unicodeTestString.toCharArray(), lStream)); lStream.close(); rs3.close(); stmt3.close(); }
Example 9
Source Project: common-utils File: StreamUtil.java License: GNU General Public License v2.0 | 5 votes |
/** 将字符串写入到指定<code>Writer</code>中。 */ public static void writeText(CharSequence chars, Writer out, boolean closeOut) throws IOException { try { out.write(chars.toString()); out.flush(); } finally { if (closeOut) { try { out.close(); } catch (IOException e) { // ignore } } } }
Example 10
Source Project: aliyun-maxcompute-data-collectors File: OracleIncrementalImportTest.java License: Apache License 2.0 | 5 votes |
private void createFileWithContent(String connPropsFileName, String fileContent) throws IOException { File file = new File(connPropsFileName); if(file.exists()) file.delete(); Writer writer = new BufferedWriter(new FileWriter(connPropsFileName)); writer.write(fileContent); writer.close(); }
Example 11
Source Project: BtPlayer File: XLLogInternal.java License: Apache License 2.0 | 5 votes |
private void logfile(LogLevel logLevel, String str, String str2) { try { Writer fileWriter = new FileWriter(getLogFile(), true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(str2); bufferedWriter.newLine(); bufferedWriter.close(); fileWriter.close(); } catch (Exception e) { } }
Example 12
Source Project: datacollector File: TestTextSpoolDirSource.java License: Apache License 2.0 | 5 votes |
@Test public void testGbkEncodedFile() throws Exception { SpoolDirSource source = createSource("GBK"); PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source).addOutputLane("lane").build(); runner.runInit(); try { // Write out a gbk-encoded file. File f = new File(createTestDir(), "test_gbk.log"); Writer writer = new OutputStreamWriter(new FileOutputStream(f), "GBK"); IOUtils.write(UTF_STRING, writer); writer.close(); // Read back the file to verify its content is gbk-encoded. BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF8")); Assert.assertEquals(GBK_STRING, reader.readLine()); reader.close(); BatchMaker batchMaker = SourceRunner.createTestBatchMaker("lane"); SpoolDirRunnable runnable = source.getSpoolDirRunnable(threadNumber, batchSize, null); Assert.assertEquals("-1", runnable.generateBatch(new LocalFileSystem("*", PathMatcherMode.GLOB).getFile(f.getAbsolutePath()), "0", 10, batchMaker)); StageRunner.Output output = SourceRunner.getOutput(batchMaker); List<Record> records = output.getRecords().get("lane"); Assert.assertNotNull(records); Assert.assertEquals(1, records.size()); Assert.assertEquals( UTF_STRING.substring(0, 10), records.get(0).get().getValueAsMap().get("text").getValueAsString() ); Assert.assertTrue(records.get(0).has("/truncated")); } finally { source.destroy(); runner.runDestroy(); } }
Example 13
Source Project: TAB File: ConfigurationFile.java License: Apache License 2.0 | 5 votes |
public void save() { try { Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8); yaml.dump(values, writer); writer.close(); if (!hasHeader()) fixHeader(); } catch (Throwable e) { Shared.errorManager.criticalError("Failed to save yaml file " + file.getPath(), e); } }
Example 14
Source Project: status File: Jackson.java License: Apache License 2.0 | 5 votes |
public static String prettyPrint(final Object o, final ObjectMapper mapper) throws IOException { final Writer sw = new StringWriter(); prettyPrint(sw, o, mapper); sw.close(); return sw.toString(); }
Example 15
Source Project: astor File: StrBuilderTest.java License: GNU General Public License v2.0 | 5 votes |
@Test public void testAsWriter() throws Exception { final StrBuilder sb = new StrBuilder("base"); final Writer writer = sb.asWriter(); writer.write('l'); assertEquals("basel", sb.toString()); writer.write(new char[] {'i', 'n'}); assertEquals("baselin", sb.toString()); writer.write(new char[] {'n', 'e', 'r'}, 1, 2); assertEquals("baseliner", sb.toString()); writer.write(" rout"); assertEquals("baseliner rout", sb.toString()); writer.write("ping that server", 1, 3); assertEquals("baseliner routing", sb.toString()); writer.flush(); // no effect assertEquals("baseliner routing", sb.toString()); writer.close(); // no effect assertEquals("baseliner routing", sb.toString()); writer.write(" hi"); // works after close assertEquals("baseliner routing hi", sb.toString()); sb.setLength(4); // mix and match writer.write('d'); assertEquals("based", sb.toString()); }
Example 16
Source Project: big-c File: TestNMWebServer.java License: Apache License 2.0 | 5 votes |
private void writeContainerLogs(Context nmContext, ContainerId containerId, LocalDirsHandlerService dirsHandler) throws IOException, YarnException { // ContainerLogDir should be created File containerLogDir = ContainerLogsUtils.getContainerLogDirs(containerId, dirsHandler).get(0); containerLogDir.mkdirs(); for (String fileType : new String[] { "stdout", "stderr", "syslog" }) { Writer writer = new FileWriter(new File(containerLogDir, fileType)); writer.write(ConverterUtils.toString(containerId) + "\n Hello " + fileType + "!"); writer.close(); } }
Example 17
Source Project: pumpernickel File: DuplexWriter.java License: MIT License | 4 votes |
@Override public void close() throws IOException { for (Writer w : writers) { w.close(); } }
Example 18
Source Project: spliceengine File: ClobUpdatableReaderTest.java License: GNU Affero General Public License v3.0 | 4 votes |
/** * Tests updates on reader. */ public void testUpdateableReader () throws Exception { getConnection().setAutoCommit (false); PreparedStatement ps = prepareStatement ("insert into updateClob " + "(id , data) values (? ,?)"); ps.setInt (1, 1); StringBuffer sb = new StringBuffer (); String base = "SampleSampleSample"; for (int i = 0; i < 100; i++) { sb.append (base); } ps.setCharacterStream (2, new StringReader (sb.toString()), sb.length()); ps.execute(); ps.close(); Statement stmt = createStatement (); ResultSet rs = stmt.executeQuery("select data from " + "updateClob where id = 1"); rs.next(); Clob clob = rs.getClob (1); rs.close(); stmt.close(); assertEquals (sb.length(), clob.length()); Reader r = clob.getCharacterStream(); char [] clobData = new char [sb.length()]; r.read (clobData); assertEquals ("mismatch from inserted string", String.valueOf (clobData), sb.toString()); r.close(); //update before gettting the reader clob.setString (50, dummy); r = clob.getCharacterStream(); r.skip (49); char [] newChars = new char [dummy.length()]; r.read (newChars); assertEquals ("update not reflected", dummy, String.valueOf (newChars)); //update again and see if stream is refreshed clob.setString (75, dummy); r.skip (75 - 50 - dummy.length()); char [] testChars = new char [dummy.length()]; r.read (testChars); assertEquals ("update not reflected", dummy, String.valueOf (newChars)); r.close(); //try inserting some unicode string String unicodeStr = getUnicodeString(); clob.setString (50, unicodeStr); char [] utf16Chars = new char [unicodeStr.length()]; r = clob.getCharacterStream(); r.skip(49); r.read(utf16Chars); assertEquals ("update not reflected", unicodeStr, String.valueOf (utf16Chars)); r.close(); Writer w = clob.setCharacterStream (1); //write enough data to switch the data to file r = clob.getCharacterStream (); for (int i = 0; i < 10000; i++) { w.write (dummy); } w.close(); clob.setString (500, unicodeStr); r.skip (499); char [] unicodeChars = new char [unicodeStr.length()]; r.read (unicodeChars); assertEquals ("update not reflected", unicodeStr, String.valueOf (unicodeChars)); }
Example 19
Source Project: velocity-engine File: ContextSafetyTestCase.java License: Apache License 2.0 | 4 votes |
/** * Runs the test. */ public void testContextSafety () throws Exception { /* * make a Vector and String array because * they are treated differently in Foreach() */ Vector v = new Vector(); v.addElement( new String("vector hello 1") ); v.addElement( new String("vector hello 2") ); v.addElement( new String("vector hello 3") ); String strArray[] = new String[3]; strArray[0] = "array hello 1"; strArray[1] = "array hello 2"; strArray[2] = "array hello 3"; VelocityContext context = new VelocityContext(); assureResultsDirectoryExists(RESULT_DIR); /* * get the template and the output */ Template template = RuntimeSingleton.getTemplate( getFileName(null, "context_safety", TMPL_FILE_EXT)); FileOutputStream fos1 = new FileOutputStream ( getFileName(RESULT_DIR, "context_safety1", RESULT_FILE_EXT)); FileOutputStream fos2 = new FileOutputStream ( getFileName(RESULT_DIR, "context_safety2", RESULT_FILE_EXT)); Writer writer1 = new BufferedWriter(new OutputStreamWriter(fos1)); Writer writer2 = new BufferedWriter(new OutputStreamWriter(fos2)); /* * put the Vector into the context, and merge */ context.put("vector", v); template.merge(context, writer1); writer1.flush(); writer1.close(); /* * now put the string array into the context, and merge */ context.put("vector", strArray); template.merge(context, writer2); writer2.flush(); writer2.close(); if (!isMatch(RESULT_DIR,COMPARE_DIR,"context_safety1", RESULT_FILE_EXT,CMP_FILE_EXT) || !isMatch(RESULT_DIR,COMPARE_DIR,"context_safety2", RESULT_FILE_EXT,CMP_FILE_EXT)) { fail("Output incorrect."); } }
Example 20
Source Project: blueocean-plugin File: Export.java License: MIT License | 4 votes |
private static void serveExposedBean(StaplerRequest req, StaplerResponse resp, Object exposedBean, ExportConfig config) throws ServletException, IOException { Flavor flavor = config.getFlavor(); String pad=null; resp.setContentType(flavor.contentType); Writer w = resp.getCompressedWriter(req); if (flavor== Flavor.JSON || flavor== Flavor.JSONP) { // for compatibility reasons, accept JSON for JSONP as well. pad = req.getParameter("jsonp"); if(pad!=null) w.write(pad+'('); } TreePruner pruner; String tree = req.getParameter("tree"); if (tree != null) { try { pruner = new NamedPathPruner(tree); } catch (IllegalArgumentException x) { throw new ServletException("Malformed tree expression: " + x, x); } } else { int depth = 0; try { String s = req.getParameter("depth"); if (s != null) { depth = Integer.parseInt(s); } } catch (NumberFormatException e) { throw new ServletException("Depth parameter must be a number"); } pruner = new ByDepth(1 - depth); } DataWriter dw = flavor.createDataWriter(exposedBean, w, config); if (exposedBean instanceof Object[]) { // TODO: extend the contract of DataWriter to capture this // TODO: make this work with XML flavor (or at least reject this better) dw.startArray(); for (Object item : (Object[])exposedBean) writeOne(pruner, dw, item); dw.endArray(); } else { writeOne(pruner, dw, exposedBean); } if(pad!=null) w.write(')'); w.close(); }