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

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

源代码1 项目: saros   文件: PackageExplorerView.java
private String convertStreamToString(InputStream is) throws IOException {
  Writer writer = new StringWriter();
  char[] buffer = new char[8192];

  try {
    Reader reader = new InputStreamReader(is, "UTF-8");
    int n;

    while ((n = reader.read(buffer)) != -1) writer.write(buffer, 0, n);

  } finally {
    is.close();
    writer.close();
  }

  return writer.toString();
}
 
源代码2 项目: document-management-software   文件: StringUtil.java
public static String writeToString(InputStream is, String targetEncoding) throws IOException {
	String enc = "UTF-8";
	if (StringUtils.isNotEmpty(targetEncoding))
		enc = targetEncoding;

	Writer writer = new StringWriter();
	char[] buffer = new char[1024];
	try {
		Reader reader = new BufferedReader(new InputStreamReader(is, enc));
		int n;
		while ((n = reader.read(buffer)) != -1) {
			writer.write(buffer, 0, n);
		}
	} finally {
		if (is != null)
			is.close();
	}
	return writer.toString();
}
 
源代码3 项目: green_android   文件: BriefLogFormatter.java
@Override
public String format(LogRecord logRecord) {
    Object[] arguments = new Object[6];
    arguments[0] = logRecord.getThreadID();
    String fullClassName = logRecord.getSourceClassName();
    int lastDot = fullClassName.lastIndexOf('.');
    String className = fullClassName.substring(lastDot + 1);
    arguments[1] = className;
    arguments[2] = logRecord.getSourceMethodName();
    arguments[3] = new Date(logRecord.getMillis());
    arguments[4] = logRecord.getMessage();
    if (logRecord.getThrown() != null) {
        Writer result = new StringWriter();
        logRecord.getThrown().printStackTrace(new PrintWriter(result));
        arguments[5] = result.toString();
    } else {
        arguments[5] = "";
    }
    return messageFormat.format(arguments);
}
 
源代码4 项目: boubei-tss   文件: EasyUtils.java
/**
 * log4j里加 log4j.logger.freemarker=fatal 过滤掉FM自身的error Log
 */
public static String fmParse( String str, Map<String, ?> data, Writer out, Configuration cfg ) {
	try {
		cfg.setNumberFormat("#"); // 防止数字类格式化,eg: 1000 变 1,000
     Template tl = new Template("t.ftl", new StringReader(str), cfg);
     tl.setEncoding("UTF-8");
     tl.process(data, out);
     str = out.toString();
     out.flush();
     
     return str;
    } 
    catch (Exception e) {
    	String errorMsg = "FM-parse-error:" + e.getMessage();
 	log.error(errorMsg);
 	log.debug("template = " + str + ", data = " + data);
 	
 	return errorMsg;
 }
}
 
源代码5 项目: material-components-android   文件: JsonReader.java
public static <T> T readJsonStream(InputStream inputStream, Type typeOfT) throws IOException {
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        int pointer;
        while ((pointer = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, pointer);
        }
    } finally {
        try {
            inputStream.close();
        } catch (IOException exception) {
            Log.e(TAG, "Error closing the input stream.", exception);
        }
    }
    String jsonString = writer.toString();
    Gson gson = new Gson();
    return gson.fromJson(jsonString, typeOfT);
}
 
源代码6 项目: spacewalk   文件: IssMasterSerializerTest.java
public void testMasterSerialize() throws XmlRpcException, IOException {
    IssMasterSerializer os = new IssMasterSerializer();
    IssMaster master = setUpMaster();

    Writer output = new StringWriter();
    os.serialize(master, output, new XmlRpcSerializer());
    String result = output.toString();
    assertEquals(os.getSupportedClass(), IssMaster.class);
    assertTrue(result.contains("<name>id</name>"));
    assertTrue(result.contains(">" + master.getId() + "<"));
    assertTrue(result.contains("name>label</name"));
    assertTrue(result.contains(">" + master.getLabel() + "<"));
    assertTrue(result.contains("name>isCurrentMaster</name"));
    assertTrue(result.contains(">" + (master.isDefaultMaster() ? "1" : "0") + "<"));
    assertTrue(result.contains("name>caCert</name"));
    assertTrue(result.contains(">" + (master.getCaCert()) + "<"));
}
 
源代码7 项目: groovy   文件: SignatureCodecVersion1.java
public String encode(final ClassNode node) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(128);
    DataOutputStream dos = new DataOutputStream(baos);
    Writer wrt = new StringBuilderWriter();
    String encoded = null;
    try {
        doEncode(node, dos);
        EncodingGroovyMethods.encodeBase64(baos.toByteArray()).writeTo(wrt);
        encoded = wrt.toString();
    } catch (IOException e) {
        throw new GroovyRuntimeException("Unable to serialize type information", e);
    }
    return encoded;
}
 
源代码8 项目: Pix-EzViewer   文件: CrashHandler.java
/**
 * 保存错误信息到文件中
 *
 * @param ex
 * @return
 */
private String saveCrashInfoToFile(Throwable ex) {
    Writer info = new StringWriter();
    PrintWriter printWriter = new PrintWriter(info);
    ex.printStackTrace(printWriter);
    Throwable cause = ex.getCause();
    while (cause != null) {
        cause.printStackTrace(printWriter);
        cause = cause.getCause();
    }
    String result = info.toString();
    printWriter.close();
    mDeviceCrashInfo.put("EXEPTION", ex.getLocalizedMessage());
    mDeviceCrashInfo.put(STACK_TRACE, result);
    try {
        //long timestamp = System.currentTimeMillis();
        Time t = new Time("GMT+8");
        t.setToNow(); // 取得系统时间
        int date = t.year * 10000 + t.month * 100 + t.monthDay;
        int time = t.hour * 10000 + t.minute * 100 + t.second;
        String fileName = "crash-" + date + "-" + time + CRASH_REPORTER_EXTENSION;
        FileOutputStream trace = mContext.openFileOutput(fileName,
                Context.MODE_PRIVATE);
        mDeviceCrashInfo.store(trace, "");
        trace.flush();
        trace.close();
        return fileName;
    } catch (Exception e) {
        Log.e(TAG, "an error occured while writing report file...", e);
    }
    return null;
}
 
源代码9 项目: client_java   文件: PrometheusEndpoint.java
public String writeRegistry(Set<String> metricsToInclude) {
  try {
    Writer writer = new StringWriter();
    TextFormat.write004(writer, collectorRegistry.filteredMetricFamilySamples(metricsToInclude));
    return writer.toString();
  } catch (IOException e) {
    // This actually never happens since StringWriter::write() doesn't throw any IOException
    throw new RuntimeException("Writing metrics failed", e);
  }
}
 
源代码10 项目: tomee   文件: AbstractCommand.java
protected String format(final String json) throws IOException {
    final StringIndenter formatter = new StringIndenter(json);
    final Writer outWriter = new StringWriter();
    IOUtils.copy(new StringReader(formatter.result()), outWriter, 2048);
    outWriter.close();
    return outWriter.toString();
}
 
源代码11 项目: freeline   文件: FreelineCore.java
public static void printStackTrace(Throwable aThrowable) {
    Writer result = new StringWriter();
    PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    String resultStr = result.toString();
    Log.e(TAG, resultStr);
}
 
源代码12 项目: spacewalk   文件: ActivationKeyHandlerTest.java
public void testGetDetails() throws Exception {
    String newKey = keyHandler.create(admin, KEY, KEY_DESCRIPTION, baseChannelLabel,
            KEY_USAGE_LIMIT, KEY_ENTITLEMENTS, Boolean.FALSE);

    Channel childChannel = ChannelTestUtils.createChildChannel(admin, baseChannel);
    String childChannelLabel = childChannel.getLabel();
    keyHandler.addChildChannels(admin, newKey, buildList(childChannelLabel));

    ServerGroup group = ServerGroupTestUtils.createManaged(admin);
    keyHandler.addServerGroups(admin, newKey,
            buildList(new Integer(group.getId().intValue())));

    PackageName newName = PackageNameTest.createTestPackageName();
    keyHandler.addPackageNames(admin, newKey, buildList(newName.getName()));

    PackageName newName2 = PackageNameTest.createTestPackageName();
    keyHandler.addPackageNames(admin, newKey, buildList(newName2.getName()));

    PackageName newName3 = PackageNameTest.createTestPackageName();
    keyHandler.addPackageNames(admin, newKey, buildList(newName3.getName()));

    ActivationKey key = keyHandler.getDetails(admin, newKey);
    Writer output = new StringWriter();
    ActivationKeySerializer serializer = new ActivationKeySerializer();
    serializer.serialize(key, output, new XmlRpcSerializer());
    String finalResult = output.toString();

    assertTrue(finalResult.indexOf(newKey) >= 0);
    assertTrue(finalResult.indexOf(KEY_DESCRIPTION) >= 0);
    assertTrue(finalResult.indexOf("<i4>" + KEY_USAGE_LIMIT + "</i4>") >= 0);
    assertTrue(finalResult.indexOf("<string>" + baseChannelLabel + "</string>") >= 0);

    assertTrue(finalResult.indexOf(newName.getName()) >= 0);
    assertTrue(finalResult.indexOf(newName2.getName()) >= 0);
    assertTrue(finalResult.indexOf(newName3.getName()) >= 0);
}
 
源代码13 项目: framework   文件: XmlBeanUtil.java
/**
 * @param object 对象
 * @return 返回xmlStr
 * @throws UtilException
 */
public static String object2Xml(final Object object) throws UtilException {
    try {
        JAXBContext context = JAXBContext.newInstance(object.getClass());

        Marshaller marshaller = context.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化输出
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 编码格式,默认为utf-8o
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // 是否省略xml头信息
        Writer writer = new CharArrayWriter();
        XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(writer);
        xmlStreamWriter.writeStartDocument((String) marshaller.getProperty(Marshaller.JAXB_ENCODING), "1.0");

        marshaller.marshal(object, xmlStreamWriter);
        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.close();
        String xml = writer.toString();
        xml = StringUtils.replace(xml, "&lt;", "<");
        xml = StringUtils.replace(xml, "&gt;", ">");
        xml = StringUtils.replace(xml, "&amp;", "&");
        xml = StringUtils.replace(xml, "&#xd;", GlobalConstants.BLANK);
        return xml;
    }
    catch (Exception e) {
        throw new UtilException(ErrorCodeDef.XML_TRANS_ERROR, e);
    }

}
 
源代码14 项目: OpenWeatherPlus-Android   文件: CrashHandler.java
/**
 * 保存错误信息到文件中
 * @return 返回文件名称, 便于将文件传送到服务器
 */
private String saveCrashInfo2File(Throwable ex) {
    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, String> entry : infos.entrySet()) {
        String key   = entry.getKey();
        String value = entry.getValue();
        sb.append(key + "=" + value + "\n");
    }

    Writer writer      = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    ex.printStackTrace(printWriter);
    Throwable cause = ex.getCause();
    while (cause != null) {
        cause.printStackTrace(printWriter);
        cause = cause.getCause();
    }
    printWriter.close();

    String result = writer.toString();
    sb.append(result);
    try {
        String time      = formatter.format(new Date());
        String fileName  = time + ".log";

        if ( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = Environment.getExternalStorageDirectory().getPath() + "/Heweather/";
            File dir  = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(path + fileName);
            fos.write(sb.toString().getBytes());
            fos.close();
        }
        Log.d(TAG, "saveCrashInfo2File: " + fileName);
        return fileName;
    } catch (Exception e) {
        Log.e(TAG, "an error occured while writing file...", e);
    }
    return null;
}
 
源代码15 项目: UltimateAndroid   文件: CrashHandler.java
/**
 * Save Info to files
 *
 * @param ex
 * @return filename
 */
private String saveCrashInfo2File(Throwable ex) {

    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, String> entry : infos.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        sb.append(key + "=" + value + "\n");
    }

    Writer writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    ex.printStackTrace(printWriter);
    Throwable cause = ex.getCause();
    while (cause != null) {
        cause.printStackTrace(printWriter);
        cause = cause.getCause();
    }
    printWriter.close();
    String result = writer.toString();
    sb.append(result);
    try {
        long timestamp = System.currentTimeMillis();
        String time = formatter.format(new Date());
        String fileName = "crash-" + time + "-" + timestamp + ".log";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            String path =
                    //StorageUtils.getCacheDirectory(mContext) +
                    Environment.getExternalStorageDirectory().getAbsolutePath() +
                            (BasicUtils.judgeNotNull(crashFilePath) ? crashFilePath : "/crash/");
            Logs.d("path----" + path);
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(path + fileName);
            fos.write(sb.toString().getBytes());
            fos.close();
        }
        return fileName;
    } catch (Exception e) {
        Logs.e("an error occured while writing file...", e);
    }
    return null;
}
 
源代码16 项目: raml-module-builder   文件: SchemaMaker.java
private String handleDelete() throws IOException, TemplateException {
  Writer writer = new StringWriter();
  Template tableTemplate = cfg.getTemplate("delete.ftl");
  tableTemplate.process(templateInput, writer);
  return writer.toString();
}
 
源代码17 项目: groovy   文件: StringGroovyMethods.java
/**
 * Return a CharSequence with lines (separated by LF, CR/LF, or CR)
 * terminated by the platform specific line separator.
 *
 * @param self a CharSequence object
 * @return the denormalized toString() of this CharSequence
 *
 * @since 1.8.2
 */
public static String denormalize(final CharSequence self) {
    // Don't do this in static initializer because we may never be needed.
    // TODO: Put this lineSeparator property somewhere everyone can use it.
    if (lineSeparator == null) {
        final Writer sw = new StringBuilderWriter(2);
        // use BufferedWriter rather than System.getProperty because it has
        // the security manager rigamarole to deal with the possible exception
        try (final BufferedWriter bw = new BufferedWriter(sw)) {
            bw.newLine();
            bw.flush();
            lineSeparator = sw.toString();
        } catch (IOException ioe) {
            // This shouldn't happen, but this is the same default used by
            // BufferedWriter on a security exception.
            lineSeparator = "\n";
        }
    }

    final int len = self.length();

    if (len < 1) {
        return self.toString();
    }

    final StringBuilder sb = new StringBuilder((110 * len) / 100);

    int i = 0;

    // GROOVY-7873: GString calls toString() on each invocation of CharSequence methods such
    // as charAt which is very expensive for large GStrings.
    CharSequence cs = (self instanceof GString) ? self.toString() : self;
    while (i < len) {
        final char ch = cs.charAt(i++);

        switch (ch) {
            case '\r':
                sb.append(lineSeparator);

                // Eat the following LF if any.
                if ((i < len) && (cs.charAt(i) == '\n')) {
                    ++i;
                }

                break;

            case '\n':
                sb.append(lineSeparator);
                break;

            default:
                sb.append(ch);
                break;
        }
    }

    return sb.toString();
}
 
源代码18 项目: aion   文件: CfgTx.java
public String toXML() {
    final XMLOutputFactory output = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlWriter;
    String xml;
    try {
        Writer strWriter = new StringWriter();
        xmlWriter = output.createXMLStreamWriter(strWriter);
        xmlWriter.writeCharacters("\r\n\t");
        xmlWriter.writeStartElement("tx");

        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeComment("Sets max TransactionPoolCaching size by 0.1MB incremental unit");
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeStartElement("cacheMax");
        xmlWriter.writeCharacters(String.valueOf(this.getCacheMax()));
        xmlWriter.writeEndElement();

        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeComment("Sets pending transaction timeout threshold in the transaction pool");
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeStartElement("txPendingTimeout");
        xmlWriter.writeCharacters(String.valueOf(this.getTxPendingTimeout()));
        xmlWriter.writeEndElement();

        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeComment("Sets the pending transactions backup to the Database");
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeStartElement("poolBackup");
        xmlWriter.writeCharacters(String.valueOf(this.getPoolBackup()));
        xmlWriter.writeEndElement();

        xmlWriter.writeCharacters("\r\n\t");
        xmlWriter.writeEndElement();
        xml = strWriter.toString();
        strWriter.flush();
        strWriter.close();
        xmlWriter.flush();
        xmlWriter.close();
        return xml;
    } catch (IOException | XMLStreamException e) {
        e.printStackTrace();
        return "";
    }
}
 
源代码19 项目: cumulusrdf   文件: Util.java
/**
 * Returns the stacktrace of a given exception.
 * 
 * @param throwable the exception.
 * @return the stacktrace as a string.
 */
public static String getStackTrace(final Throwable throwable) {
	final Writer result = new StringWriter();
	throwable.printStackTrace(new PrintWriter(result));
	return result.toString();
}
 
源代码20 项目: pegasus   文件: PCRelation.java
/**
 * Returns the DOT description of the object. This is used for visualizing the workflow.
 *
 * @return String containing the Partition object in XML.
 * @exception IOException if something fishy happens to the stream.
 */
public String toDOT() throws IOException {
    Writer writer = new StringWriter(32);
    toDOT(writer, "");
    return writer.toString();
}