Java 类org.apache.commons.io.output.StringBuilderWriter 实例源码

项目:osc-core    文件:ServerControl.java   
private static void offlineQuery(String sql) throws IOException {
    StringBuilder output = new StringBuilder();
    output.append("Query: ").append(sql).append("\n");

    DBConnectionParameters params = new DBConnectionParameters();

    try (Connection conn = DriverManager.getConnection(params.getConnectionURL(),
            params.getLogin(), params.getPassword());
         Statement statement = conn.createStatement()) {
        try (ResultSet result = statement.executeQuery(sql)){
            processResultSetForQuery(output, result);
        }
    } catch (Exception ex) {
        try (PrintWriter pw = new PrintWriter(new StringBuilderWriter(output), true)) {
            ex.printStackTrace(pw);
        }
    }

    System.out.println(output.toString());
}
项目:osc-core    文件:ServerControl.java   
private static void offlineExec(String sql) throws IOException {
    StringBuilder output = new StringBuilder();
    output.append("Exec: ").append(sql).append("\n");

    DBConnectionParameters params = new DBConnectionParameters();

    try (Connection conn = DriverManager.getConnection(params.getConnectionURL(),
            params.getLogin(), params.getPassword());
         Statement statement = conn.createStatement()) {
        boolean isResultSet = statement.execute(sql);
        if (!isResultSet) {
            output.append(statement.getUpdateCount()).append(" rows affected.\n");
        }
    } catch (Exception ex) {
        try (PrintWriter pw = new PrintWriter(new StringBuilderWriter(output), true)) {
            ex.printStackTrace(pw);
        }
    }
    System.out.println(output.toString());
}
项目:QDrill    文件:ValueHolderReplacementVisitor.java   
@Override
public void visitEnd() {
  try {
    accept(inner);
    super.visitEnd();
  } catch(Exception e){
    Textifier t = new Textifier();
    accept(new TraceMethodVisitor(t));
    StringBuilderWriter sw = new StringBuilderWriter();
    PrintWriter pw = new PrintWriter(sw);
    t.print(pw);
    pw.flush();
    String bytecode = sw.getBuilder().toString();
    logger.error(String.format("Failure while rendering method %s, %s, %s.  ByteCode:\n %s", name, desc, signature, bytecode), e);
    throw new RuntimeException(String.format("Failure while rendering method %s, %s, %s.  ByteCode:\n %s", name, desc, signature, bytecode), e);
  }
}
项目:MCLibrary    文件:GsonUtils.java   
public static <T> Optional<T> read(Gson gson, File file, Type type) {
    T ret = null;

    if (file.isFile()) {
        StringBuilder builder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null)
                builder.append(line).append('\n');
            ret = read(gson, new StringReader(builder.toString()), type);
        } catch (Exception e) {
            Static.log("Error while read " + file.getName());
            e.printStackTrace();

            // Log file & Backup
            builder.append('\n').append("=== 에러 로그 (수정&적용 시 이 부분을 지우세요) ===").append('\n');
            e.printStackTrace(new PrintWriter(new StringBuilderWriter(builder)));
            File backupFile = FileUtils.appendToName(file, "-" + System.currentTimeMillis(), ".broken");
            FileUtils.write(backupFile, builder);
        }
    }

    return Optional.ofNullable(ret);
}
项目:oma-riista-web    文件:WFSUtil.java   
public static String domToString(final Node doc,
                                 final boolean pretty,
                                 final boolean omitXml) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXml ? "yes" : "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, pretty ? "yes" : "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        if (pretty) {
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        }

        try (StringBuilderWriter writer = new StringBuilderWriter()) {
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            return writer.getBuilder().toString();
        }
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}
项目:Gargoyle    文件:ValueUtil.java   
/**
 * 에러 메세지 상세화
 *
 * @param title
 *            메세지 타이틀
 * @param e
 * @return
 */
public static String toString(String title, Throwable e) {
    if (e == null)
        return "[warnning] Exception is null";

    String errMsg = "";
    try (StringBuilderWriter sbw = new StringBuilderWriter()) {
        try (PrintWriter printWriter = new PrintWriter(sbw, true)) {
            if (title != null)
                printWriter.write("#############  ".concat(title).concat("  ##############\n"));
            e.printStackTrace(printWriter);
        }
        errMsg = sbw.toString();
    }
    return errMsg;
}
项目:Gargoyle    文件:ValueUtil.java   
/**
 * 에러 메세지 상세화
 *
 * @param title
 *            메세지 타이틀
 * @param e
 * @return
 */
public static String toString(String title, Throwable e) {
    if (e == null)
        return "[warnning] Exception is null";

    String errMsg = "";
    try (StringBuilderWriter sbw = new StringBuilderWriter()) {
        try (PrintWriter printWriter = new PrintWriter(sbw, true)) {
            if (title != null)
                printWriter.write("#############  ".concat(title).concat("  ##############\n"));
            e.printStackTrace(printWriter);
        }
        errMsg = sbw.toString();
    }
    return errMsg;
}
项目:app-runner    文件:AppResource.java   
@POST /* Maybe should be PUT, but too many hooks only use POST */
@Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON})
@Path("/{name}/deploy")
@ApiOperation(value = "Deploys an app", notes = "Deploys the app by fetching the latest changes from git, building it, " +
    "starting it, polling for successful startup by making GET requests to /{name}/, and if it returns any HTTP response " +
    "it shuts down the old version of the app. If any steps before that fail, the old version of the app will continue serving " +
    "requests.")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Returns 200 if the command was received successfully. Whether the build " +
    "actually succeeds or fails is ignored. Returns streamed plain text of the build log and console startup, unless the Accept" +
    " header includes 'application/json'.")})
public Response deploy(@Context UriInfo uriInfo, @ApiParam(example = "application/json") @HeaderParam("Accept") String accept,
                       @ApiParam(required = true, example = "app-runner-home") @PathParam("name") String name) throws IOException {
    StreamingOutput stream = new UpdateStreamer(name);
    if (MediaType.APPLICATION_JSON.equals(accept)) {
        StringBuilderWriter output = new StringBuilderWriter();
        try (WriterOutputStream writer = new WriterOutputStream(output)) {
            stream.write(writer);
            return app(uriInfo, name);
        }
    } else {
        return Response.ok(stream).build();
    }
}
项目:app-runner    文件:SystemInfo.java   
private static List<String> getPublicKeys() throws Exception {
    return new JschConfigSessionFactory() {
        @Override
        protected void configure(OpenSshConfig.Host hc, Session session) {
        }
        List<String> getPublicKeys() throws Exception {
            JSch jSch = createDefaultJSch(FS.DETECTED);
            List<String> keys = new ArrayList<>();
            for (Object o : jSch.getIdentityRepository().getIdentities()) {
                Identity i = (Identity) o;
                KeyPair keyPair = KeyPair.load(jSch, i.getName(), null);
                StringBuilder sb = new StringBuilder();
                try (StringBuilderWriter sbw = new StringBuilderWriter(sb);
                     OutputStream os = new WriterOutputStream(sbw, "UTF-8")) {
                    keyPair.writePublicKey(os, keyPair.getPublicKeyComment());
                } finally {
                    keyPair.dispose();
                }
                keys.add(sb.toString().trim());
            }
            return keys;
        }
    }.getPublicKeys();
}
项目:app-runner    文件:ProcessStarterTest.java   
static void startAndStop(int attempt, String appName, AppRunner runner, int port, StringBuilderWriter buildLog, StringBuilderWriter consoleLog, Matcher<String> getResponseMatcher, Matcher<String> buildLogMatcher) throws Exception {
    try {
        try (Waiter startupWaiter = Waiter.waitForApp(appName, port)) {
            runner.start(
                new OutputToWriterBridge(buildLog),
                new OutputToWriterBridge(consoleLog),
                TestConfig.testEnvVars(port, appName),
                startupWaiter);
        }
        try {
            ContentResponse resp = httpClient.GET("http://localhost:" + port + "/" + appName + "/");
            assertThat(resp.getStatus(), is(200));
            assertThat(resp.getContentAsString(), getResponseMatcher);
            assertThat(buildLog.toString(), buildLogMatcher);
        } finally {
            runner.shutdown();
        }
    } catch (Exception e) {
        clearlyShowError(attempt, e, buildLog, consoleLog);
    }
}
项目:drill    文件:ValueHolderReplacementVisitor.java   
@Override
public void visitEnd() {
  try {
    accept(inner);
    super.visitEnd();
  } catch(Exception e){
    Textifier t = new Textifier();
    accept(new TraceMethodVisitor(t));
    StringBuilderWriter sw = new StringBuilderWriter();
    PrintWriter pw = new PrintWriter(sw);
    t.print(pw);
    pw.flush();
    String bytecode = sw.getBuilder().toString();
    logger.error(String.format("Failure while rendering method %s, %s, %s.  ByteCode:\n %s", name, desc, signature, bytecode), e);
    throw new RuntimeException(String.format("Failure while rendering method %s, %s, %s.  ByteCode:\n %s", name, desc, signature, bytecode), e);
  }
}
项目:java-opencage-geocoder    文件:JsonDeserializationTest.java   
private String loadData(String name)
{
    String data = null;

    InputStream reader = getClass().getClassLoader().getResourceAsStream(name);

    StringBuilder output = new StringBuilder();
    StringBuilderWriter writer = new StringBuilderWriter(output);

    try
    {
        IOUtils.copy(reader, writer);
    }
    catch (IOException ioe)
    {
        LOGGER.error("While loading test data", ioe);
    }

    data = writer.toString();

    return data;
}
项目:plugin-datasource    文件:CsvExportService.java   
private String convertDataToCsv(final RequestResultDTO requestResult, boolean withHeader) {
    LOG.debug("convertDataToCsv - called for {}, withHeader={}", requestResult, withHeader);

    final StringBuilder sb = new StringBuilder();
    try (
        final Writer writer = new StringBuilderWriter(sb);
        final CSVWriter csvWriter = new CSVWriter(writer)) {

        // header
        if (withHeader) {
            csvWriter.writeNext(requestResult.getHeaderLine().toArray(new String[0]));
        }

        // body
        for (final List<String> line : requestResult.getResultLines()) {
            csvWriter.writeNext(line.toArray(new String[0]));
        }
    } catch (final IOException e) {
        LOG.error("Close failed on resource - expect leaks and incorrect operation", e);
    }

    return sb.toString();
}
项目:bsonpatch    文件:AbstractTest.java   
private String errorMessage(String header, Exception e) {

        StringBuilder res =
                new StringBuilder()
                        .append(header)
                        .append("\nFull test case (in file ")
                        .append(p.getSourceFile())
                        .append("):\n")
                        .append(p.getNode().toJson(jwsettings));
        if (e != null) {
            res.append("\nFull error: ");
            e.printStackTrace(new PrintWriter(new StringBuilderWriter(res)));
        }
        return res.toString();
    }
项目:docx4j-template    文件:WordprocessingMLTemplateWriter.java   
public String writeToString(File docFile) throws IOException, Docx4JException {
    WordprocessingMLPackage wmlPackage = WordprocessingMLPackage.load(docFile);
    StringBuilderWriter output = new StringBuilderWriter();
    try {
        this.writeToWriter(wmlPackage, output);
    } finally {
        IOUtils.closeQuietly(output);
    }
    return output.toString();
}
项目:docx4j-template    文件:WordprocessingMLPackageExtractor.java   
public String extract(File inputfile) throws Exception {
    WordprocessingMLPackage wmlPackage = WordprocessingMLPackage.load(inputfile);
    StringBuilderWriter output = new StringBuilderWriter();
    try {
        this.extract(wmlPackage, output);
    } finally {
        IOUtils.closeQuietly(output);
    }
    return output.toString();
}
项目:docx4j-template    文件:WordprocessingMLPackageExtractor.java   
public String extract(WordprocessingMLPackage wmlPackage) throws Exception {
    StringBuilderWriter output = new StringBuilderWriter(); 
    try {
        this.extract(wmlPackage, output);
    } finally {
        IOUtils.closeQuietly(output);
    }
    return output.toString();
}
项目:app-runner    文件:ProcessStarterTest.java   
static void clearlyShowError(int attempt, Exception e, StringBuilderWriter buildLog, StringBuilderWriter consoleLog) throws Exception {
    System.out.println("Failure on attempt " + attempt);
    System.out.println("Build log");
    System.out.println(buildLog);
    System.out.println();
    System.out.println("Console log");
    System.out.println(consoleLog);
    throw e;
}
项目:template-compiler    文件:GeneralUtils.java   
/**
 * Formats the {@code node} as a string using the pretty printer.
 */
public static String jsonPretty(JsonNode node) throws IOException {
  StringBuilder buf = new StringBuilder();
  JsonGenerator gen = JSON_FACTORY.createGenerator(new StringBuilderWriter(buf));
  gen.useDefaultPrettyPrinter();
  gen.setCodec(JsonUtils.getMapper());
  gen.writeTree(node);
  return buf.toString();
}
项目:openmeetings    文件:ErrorMessagePanel.java   
public ErrorMessagePanel(String id, String msg, Throwable err) {
    super(id);

    log.error(msg, err);
    add(new Label("msg", msg));
    StringBuilderWriter sw = new StringBuilderWriter();
    err.printStackTrace(new PrintWriter(sw));
    add(new Label("err", sw.toString()));
}
项目:Tilda    文件:Sql.java   
@Override
public void genDDLComments(PrintWriter OutFinal, View V)
throws Exception
  {
    StringBuilderWriter Str = new StringBuilderWriter();
    PrintWriter Out = new PrintWriter(Str);
    genDDL(Out, V);

    OutFinal.println("COMMENT ON VIEW " + V._ParentSchema._Name + "." + V._Name + " IS E" + TextUtil.EscapeSingleQuoteForSQL(Str.toString().replace("\r\n", "\\n").replace("\n", "\\n")) + ";");
    OutFinal.println();
    for (int i = 0; i < V._ViewColumns.size(); ++i)
      {
        ViewColumn VC = V._ViewColumns.get(i);
        if (V._Pivot != null)
          {
            if (VC == V._Pivot._VC // This is the pivot column
            || i == V._ViewColumns.size() - 1 // This is the last column (either count(*) or something else)
            // || VC._Aggregate == AggregateType.COUNT // This is the final count(*) column, so no comment
            )
              continue; // no comment
          }
        if (VC != null && VC._SameAsObj != null && VC._SameAsObj._Mode != ColumnMode.CALCULATED && VC._JoinOnly == false)
          OutFinal.println("COMMENT ON COLUMN " + V.getShortName() + ".\"" + VC.getName() + "\" IS E" + TextUtil.EscapeSingleQuoteForSQL(VC._SameAsObj._Description) + ";");
      }
    if (V._Pivot != null)
      for (int i = 0; i < V._Pivot._Values.length; ++i)
        OutFinal.println("COMMENT ON COLUMN " + V.getShortName() + ".\"" + TextUtil.Print(V._Pivot._Values[i]._Name, V._Pivot._Values[i]._Value) + "\" IS E"
        + TextUtil.EscapeSingleQuoteForSQL("The pivoted column count from '" + V._Pivot._ColumnName + "'='" + V._Pivot._Values[i]._Value + "', " + V._Pivot._Values[i]._Description)
        + ";");
    if (V._Formulas != null)
      for (Formula F : V._Formulas)
        if (F != null)
          OutFinal.println("COMMENT ON COLUMN " + V.getShortName() + ".\"" + F._Name + "\" IS E"
          + TextUtil.EscapeSingleQuoteForSQL("The calculated formula: " + String.join("\\n", F._Description))
          + ";");
  }
项目:springmvc-raml-plugin    文件:CodeModelHelper.java   
/**
 * Returns the string equivalent of the code model element
 * @param type The element to stringify
 * @return the element as a string (generated code)
 */
public static String getElementAsString(JDeclaration type) {
    StringBuilder builder = new StringBuilder();
    JFormatter jFormatter = new JFormatter(new StringBuilderWriter(builder));
    type.declare(jFormatter);
    return builder.toString();
}
项目:oap    文件:ElasticSearchSchema.java   
@SneakyThrows
public static String convert( SchemaAST<?> schemaAST ) {
    val jfactory = new JsonFactory();
    val stringBuilder = new StringBuilder();
    try( val stringBuilderWriter = new StringBuilderWriter( stringBuilder );
         val jsonGenerator = jfactory.createGenerator( stringBuilderWriter ) ) {
        jsonGenerator.writeStartObject();
        convert( schemaAST, jsonGenerator, true );
        jsonGenerator.writeEndObject();
    }

    return stringBuilder.toString();
}
项目:Zom-Android    文件:Debug.java   
static public void wrapExceptions(Runnable runnable) {
    try {
        runnable.run();
    } catch (Throwable t) {
        StringBuilderWriter writer = new StringBuilderWriter();
        PrintWriter pw = new PrintWriter(writer, true);
        t.printStackTrace(pw);
        writer.flush();
        throw new IllegalStateException("service throwable: " + writer.getBuilder().toString());
    }
}
项目:ds3_java_sdk    文件:AggregateException.java   
public String toString() {
    final StringBuilder builder = new StringBuilder();
    builder.append("One or more exceptions were aggregated:");

    try (final StringBuilderWriter writer = new StringBuilderWriter(builder);
         final PrintWriter printWriter = new PrintWriter(writer)) {

        for (final Throwable t : exceptions) {
            printWriter.append("Exception: ").append(t.getMessage());
            t.printStackTrace(printWriter);
        }
    }

    return builder.toString();
}
项目:orm-benchmark    文件:CsvWriterTest.java   
@Benchmark
public CharSequence writeObjectJackson() throws Exception {
    StringBuilderWriter sbw = new StringBuilderWriter(CAPACITY);

    myObjectWriter.writeValue(sbw, sbo);

    return sbw.getBuilder();
}
项目:orm-benchmark    文件:CsvWriterTest.java   
@Benchmark
public CharSequence writeObjectUnivocity() throws Exception {
    StringBuilderWriter sbw = new StringBuilderWriter(CAPACITY);

    com.univocity.parsers.csv.CsvWriter writer = new  com.univocity.parsers.csv.CsvWriter(sbw, settings);
    writer.processRecord(sbo);
    return sbw.getBuilder();
}
项目:zjsonpatch    文件:AbstractTest.java   
private String errorMessage(String header, Exception e) throws JsonProcessingException {
    StringBuilder res =
            new StringBuilder()
                    .append(header)
                    .append("\nFull test case (in file ")
                    .append(p.getSourceFile())
                    .append("):\n")
                    .append(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(p.getNode()));
    if (e != null) {
        res.append("\nFull error: ");
        e.printStackTrace(new PrintWriter(new StringBuilderWriter(res)));
    }
    return res.toString();
}
项目:solr-fusion    文件:SolrFusionServletTest.java   
protected String runRequest(Map<String, String[]> reqParams, SolrFusionServlet servlet, HttpServletRequest req)
    throws IOException
{
    doReturn(new HashMap<>()).when(servlet).collectHeader(req);
    doReturn(reqParams).when(req).getParameterMap();
    HttpServletResponse res = mock(HttpServletResponse.class);
    StringBuilderWriter out = new StringBuilderWriter();
    PrintWriter pw = new PrintWriter(out);
    doReturn(pw).when(res).getWriter();
    servlet.doGet(req, res);
    ArgumentCaptor<String> msgArg = ArgumentCaptor.forClass(String.class);
    verify(res).sendError(eq(400), msgArg.capture());
    return msgArg.getValue();
}
项目:JHazm    文件:Runner.java   
private static void showHelp(Options options) {
    HelpFormatter formatter = new HelpFormatter();
    final StringBuilder helpBuilder = new StringBuilder().append('\n');
    helpBuilder.append("Welcome to JHazm.").append('\n');
    PrintWriter pw = new PrintWriter(new StringBuilderWriter(helpBuilder));
    formatter.printHelp(pw, 80, "java -jar jhazm.jar", null,
            options, 0, 0, "Thank you", false);
    helpBuilder.append("Required options for stemmer: --i or --t, --o").append('\n');
    System.err.println(helpBuilder);
    System.exit(0);
}
项目:prive-android    文件:Debug.java   
static public void wrapExceptions(Runnable runnable) {
    try {
        runnable.run();
    } catch (Throwable t) {
        StringBuilderWriter writer = new StringBuilderWriter();
        PrintWriter pw = new PrintWriter(writer, true);
        t.printStackTrace(pw);
        writer.flush();
        throw new IllegalStateException("service throwable: " + writer.getBuilder().toString());
    }
}
项目:apt    文件:AbstractRenderer.java   
@Override
public String render(G obj) throws RenderException {
    try (Writer writer = new StringBuilderWriter()) {
        render(obj, writer);
        return writer.toString();
    } catch (IOException e) {
        // A StringWriter shouldn't throw IOExceptions
        throw new RuntimeException(e);
    }
}
项目:apiman    文件:XContentBuilder.java   
/**
 * Constructor.
 */
public XContentBuilder() {
    try {
        writer = new StringBuilderWriter();
        json = jsonFactory.createGenerator(writer);
    } catch (IOException e) {
        // Will never happen!
        throw new RuntimeException(e);
    }
}
项目:apiman    文件:RestExceptionMapper.java   
/**
 * Gets the full stack trace for the given exception and returns it as a
 * string.
 * @param data
 */
private String getStackTrace(AbstractRestException data) {
    StringBuilderWriter writer = new StringBuilderWriter();
    try {
        data.printStackTrace(new PrintWriter(writer));
        return writer.getBuilder().toString();
    } finally {
        writer.close();
    }
}
项目:apiman    文件:RestExceptionMapper.java   
/**
 * Gets the full stack trace for the given exception and returns it as a
 * string.
 * @param data
 */
private String getStackTrace(AbstractEngineException data) {
    try (StringBuilderWriter writer = new StringBuilderWriter()) {
        data.printStackTrace(new PrintWriter(writer));
        return writer.getBuilder().toString();
    }
}
项目:apiman    文件:RestExceptionMapper.java   
/**
 * Gets the full stack trace for the given exception and returns it as a
 * string.
 * @param data
 */
private String getStackTrace(AbstractEngineException data) {
    try (StringBuilderWriter writer = new StringBuilderWriter()) {
        data.printStackTrace(new PrintWriter(writer));
        return writer.getBuilder().toString();
    }
}
项目:bacoma    文件:VelocityRenderer.java   
public void render(StringBuilderWriter writer, IRenderable renderable, ViewMode viewMode) {
    render(writer, renderable, viewMode, null);
}
项目:jtestplatform    文件:OutputStreamTest.java   
public static OutputStream outputStream(StringBuilder output) {
    return new WriterOutputStream(new StringBuilderWriter(output), Charset.defaultCharset(), 1024, true);
}
项目:rodimus    文件:RodimusCli.java   
public static void transformDocument(File inputFile, File outputDir, boolean verbose) throws Exception {
  StreamSource xhtmlHandlerSource = createStreamSource(RodimusCli.class.getResource("/rodimus.xsl"));

  File indexFile = new File(outputDir, "index.html");
  File assetDir = new File(outputDir, IMAGE_DIR_NAME);
  assetDir.mkdirs();

  // Set up the output buffer.
  StringBuilderWriter output = new StringBuilderWriter();

  // Set up the serializer.
  ToXMLStream serializer = new ToXMLStream();
  serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT,String.valueOf(2));
  serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR,"\n");
  serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_ENTITIES, "yes");
  serializer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
  serializer.setWriter(output);

  // Set up the xhtmlStructure handler.
  TransformerHandler xhtmlHandler = getContentHandler(xhtmlHandlerSource);
  xhtmlHandler.setResult(new SAXResult(serializer));

  // build the Tika handler.
  ParseContext context = createParseContext(assetDir, verbose);
  PostTikaHandler cleanUp = new PostTikaHandler(IMAGE_DIR_NAME);
  cleanUp.setContentHandler(xhtmlHandler);
  parseInput(createInputStream(inputFile), cleanUp, context, verbose);

  // Do some regular expression cleanup.
  String preOutput = output.toString();
  preOutput = preOutput.replaceAll("/>", " />");
  // TODO: img is in this list, but it is not a block level element.
  String blockLevel = "(?:address|article|aside|audio|blockquote|canvas|dd|div|dl|fieldset|figcaption|figure|footer|form|h[1-6]|header|hgroup|hr|noscript|ol|output|p|pre|sectop|table|tfoot|ul|video|img)";
  preOutput = preOutput.replaceAll("(</"+blockLevel+">)(\\s*)(<"+blockLevel+")", "$1$2$2$3");
  preOutput = "<!doctype html>\n"+preOutput;

  FileUtils.write(indexFile, preOutput, "UTF-8");

  // Clean out images dir if it's empty
  if (assetDir.list().length == 0) {
    FileUtils.deleteQuietly(assetDir);
  }
}
项目:Moenagade    文件:IOUtils.java   
/**
 * Get the contents of an <code>InputStream</code> as a String
 * using the specified character encoding.
 * <p>
 * Character encoding names can be found at
 * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
 * <p>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedInputStream</code>.
 * 
 * @param input  the <code>InputStream</code> to read from
 * @param encoding  the encoding to use, null means platform default
 * @return the requested String
 * @throws NullPointerException if the input is null
 * @throws IOException if an I/O error occurs
 */
public static String toString(InputStream input, String encoding)
        throws IOException {
    StringBuilderWriter sw = new StringBuilderWriter();
    copy(input, sw, encoding);
    return sw.toString();
}