下面列出了java.io.Writer#toString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
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();
}
@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);
}
/**
* 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;
}
}
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);
}
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()) + "<"));
}
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;
}
/**
* 保存错误信息到文件中
*
* @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;
}
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);
}
}
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();
}
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);
}
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);
}
/**
* @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, "<", "<");
xml = StringUtils.replace(xml, ">", ">");
xml = StringUtils.replace(xml, "&", "&");
xml = StringUtils.replace(xml, "
", GlobalConstants.BLANK);
return xml;
}
catch (Exception e) {
throw new UtilException(ErrorCodeDef.XML_TRANS_ERROR, e);
}
}
/**
* 保存错误信息到文件中
* @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;
}
/**
* 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;
}
private String handleDelete() throws IOException, TemplateException {
Writer writer = new StringWriter();
Template tableTemplate = cfg.getTemplate("delete.ftl");
tableTemplate.process(templateInput, writer);
return writer.toString();
}
/**
* 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();
}
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 "";
}
}
/**
* 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();
}
/**
* 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();
}