java.io.Writer#close ( )源码实例Demo

下面列出了java.io.Writer#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: twill   文件: TrackerService.java
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);
}
 
源代码2 项目: wallpaper   文件: StreamUtils.java
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;
	}
}
 
源代码3 项目: hottub   文件: T6759996.java
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();
    }
}
 
源代码4 项目: secure-data-service   文件: SelectorDoc.java
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;
    }
 
源代码5 项目: ontopia   文件: TestTMRAPOperation.java
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));
}
 
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());
}
 
源代码7 项目: mobi   文件: OntologyRest.java
/**
 * 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);
    }
}
 
源代码8 项目: gemfirexd-oss   文件: LobStreamsTest.java
/**
 * 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();
}
 
源代码9 项目: common-utils   文件: StreamUtil.java
/** 将字符串写入到指定<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
            }
        }
    }
}
 
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();
}
 
源代码11 项目: BtPlayer   文件: XLLogInternal.java
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) {
    }
}
 
源代码12 项目: datacollector   文件: TestTextSpoolDirSource.java
@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();
  }
}
 
源代码13 项目: TAB   文件: ConfigurationFile.java
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);
	}
}
 
源代码14 项目: status   文件: Jackson.java
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();
}
 
源代码15 项目: astor   文件: StrBuilderTest.java
@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());
}
 
源代码16 项目: big-c   文件: TestNMWebServer.java
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();
  }
}
 
源代码17 项目: pumpernickel   文件: DuplexWriter.java
@Override
public void close() throws IOException {
	for (Writer w : writers) {
		w.close();
	}
}
 
源代码18 项目: spliceengine   文件: ClobUpdatableReaderTest.java
/**
 * 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));
}
 
源代码19 项目: velocity-engine   文件: ContextSafetyTestCase.java
/**
 * 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.");
    }
}
 
源代码20 项目: blueocean-plugin   文件: Export.java
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();
}