本文整理汇总了Java中java.io.StringWriter类的典型用法代码示例。如果您正苦于以下问题:Java StringWriter类的具体用法?Java StringWriter怎么用?Java StringWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
StringWriter类属于java.io包,在下文中一共展示了StringWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testRedirect
import java.io.StringWriter; //导入依赖的package包/类
/**
* @bug 8165116
* Verifies that redirect works properly when extension function is enabled
*
* @param xml the XML source
* @param xsl the stylesheet that redirect output to a file
* @param output the output file
* @param redirect the redirect file
* @throws Exception if the test fails
**/
@Test(dataProvider = "redirect")
public void testRedirect(String xml, String xsl, String output, String redirect) throws Exception {
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(ORACLE_ENABLE_EXTENSION_FUNCTION, true);
Transformer t = tf.newTransformer(new StreamSource(new StringReader(xsl)));
//Transform the xml
tryRunWithTmpPermission(
() -> t.transform(new StreamSource(new StringReader(xml)), new StreamResult(new StringWriter())),
new FilePermission(output, "write"), new FilePermission(redirect, "write"));
// Verifies that the output is redirected successfully
String userDir = getSystemProperty("user.dir");
Path pathOutput = Paths.get(userDir, output);
Path pathRedirect = Paths.get(userDir, redirect);
Assert.assertTrue(Files.exists(pathOutput));
Assert.assertTrue(Files.exists(pathRedirect));
System.out.println("Output to " + pathOutput + " successful.");
System.out.println("Redirect to " + pathRedirect + " successful.");
Files.deleteIfExists(pathOutput);
Files.deleteIfExists(pathRedirect);
}
示例2: save
import java.io.StringWriter; //导入依赖的package包/类
@Override
public RegisteredService save(final RegisteredService service) {
logger.debug("Saving service {}", service);
if (service.getId() == AbstractRegisteredService.INITIAL_IDENTIFIER_VALUE) {
((AbstractRegisteredService) service).setId(service.hashCode());
}
final StringWriter stringWriter = new StringWriter();
registeredServiceJsonSerializer.toJson(stringWriter, service);
couchbase.bucket().upsert(
RawJsonDocument.create(
String.valueOf(service.getId()),
0, stringWriter.toString()));
return service;
}
示例3: printLogAndReturn
import java.io.StringWriter; //导入依赖的package包/类
/**
* Print the created XML to verify. Usage: return printLogAndReturn(new JAXBElement(rootElementName, StoreOperationInput.class, input));
*
* @return JAXBElement - same object which came as input.
*/
private static JAXBElement printLogAndReturn(JAXBElement jaxbElement) {
try {
// Create a String writer object which will be
// used to write jaxbElment XML to string
StringWriter writer = new StringWriter();
// create JAXBContext which will be used to update writer
JAXBContext context = JAXBContext.newInstance(StoreOperationInput.class);
// marshall or convert jaxbElement containing student to xml format
context.createMarshaller().marshal(jaxbElement, writer);
// print XML string representation of Student object
System.out.println(writer.toString());
}
catch (JAXBException e) {
e.printStackTrace();
}
return jaxbElement;
}
示例4: xmlFormat
import java.io.StringWriter; //导入依赖的package包/类
/**
* xml 格式化
*
* @param xml
* @return
*/
public static String xmlFormat(String xml) {
if (TextUtils.isEmpty(xml)) {
return "Empty/Null xml content";
}
String message;
try {
Source xmlInput = new StreamSource(new StringReader(xml));
StreamResult xmlOutput = new StreamResult(new StringWriter());
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
message = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
} catch (TransformerException e) {
message = xml;
}
return message;
}
示例5: test_writer_1
import java.io.StringWriter; //导入依赖的package包/类
public void test_writer_1() throws Exception {
StringWriter strOut = new StringWriter();
SerializeWriter out = new SerializeWriter(strOut, 6);
out.config(SerializerFeature.QuoteFieldNames, true);
try {
JSONSerializer serializer = new JSONSerializer(out);
VO vo = new VO();
vo.setValue(123456789);
serializer.write(vo);
} finally {
out.close();
}
Assert.assertEquals("{\"value\":123456789}", strOut.toString());
}
示例6: toMemJSONString
import java.io.StringWriter; //导入依赖的package包/类
/**
* Returns the JSON string representation of the current resources allocated
* over time
*
* @return the JSON string representation of the current resources allocated
* over time
*/
public String toMemJSONString() {
StringWriter json = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(json);
readLock.lock();
try {
jsonWriter.beginObject();
// jsonWriter.name("timestamp").value("resource");
for (Map.Entry<Long, Resource> r : cumulativeCapacity.entrySet()) {
jsonWriter.name(r.getKey().toString()).value(r.getValue().toString());
}
jsonWriter.endObject();
jsonWriter.close();
return json.toString();
} catch (IOException e) {
// This should not happen
return "";
} finally {
readLock.unlock();
}
}
示例7: write
import java.io.StringWriter; //导入依赖的package包/类
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
try {
if (object == null) {
serializer.writeNull();
return;
}
Clob clob = (Clob) object;
Reader reader = clob.getCharacterStream();
StringWriter writer = new StringWriter();
char[] buf = new char[1024];
int len = 0;
while ((len = reader.read(buf)) != -1) {
writer.write(buf, 0, len);
}
reader.close();
String text = writer.toString();
serializer.write(text);
} catch (SQLException e) {
throw new IOException("write clob error", e);
}
}
示例8: generateHippoEcmExtensions
import java.io.StringWriter; //导入依赖的package包/类
@Test
public void generateHippoEcmExtensions() throws URISyntaxException, IOException, JAXBException {
URI resourceURI = getClass().getResource("").toURI();
File root = new File(resourceURI);
List<ScriptClass> scriptClasses = ScriptClassFactory.getScriptClasses(root);
Node node = XmlGenerator.getEcmExtensionNode(root, new File(root, "target"), scriptClasses, "my-updater-prefix-");
StringWriter writer = new StringWriter();
getMarshaller().marshal(node, writer);
final String xml = writer.toString();
URL testfileResultUrl = getClass().getResource("resulting-hippoecm-extension.xml");
File resultFile = new File(testfileResultUrl.toURI());
String expectedContent = FileUtils.fileRead(resultFile);
assertEquals(expectedContent, xml);
}
示例9: btnStackActionPerformed
import java.io.StringWriter; //导入依赖的package包/类
private void btnStackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStackActionPerformed
StringWriter sw = new StringWriter();
exception.printStackTrace(new PrintWriter(sw));
JPanel pnl = new JPanel();
pnl.setLayout(new BorderLayout());
pnl.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
JTextArea ta = new JTextArea();
ta.setText(sw.toString());
ta.setEditable(false);
JScrollPane pane = new JScrollPane(ta);
pnl.add(pane);
pnl.setMaximumSize(new Dimension(600, 300));
pnl.setPreferredSize(new Dimension(600, 300));
NotifyDescriptor.Message nd = new NotifyDescriptor.Message(pnl);
DialogDisplayer.getDefault().notify(nd);
}
示例10: obj2xml
import java.io.StringWriter; //导入依赖的package包/类
public static String obj2xml(Object o, Class<?> clazz) throws JAXBException {
if(null == o){
throw new InvalidParameterException();
}
JAXBContext context = JAXBContext.newInstance(clazz);
Marshaller marshaller = context.createMarshaller();
//
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// 是否去掉头部信息
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(o, writer);
return writer.toString();
}
示例11: handleProcessFailure
import java.io.StringWriter; //导入依赖的package包/类
private void handleProcessFailure(final Process failedProcess,
final String[] execCmd, final int result) throws IOException {
try (StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw)) {
pw.append("error=").append(Integer.toString(result));
pw.append(" running:");
for (String arg: execCmd) {
pw.append(" '").append(arg).append("'");
}
try (InputStream is = failedProcess.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr)) {
while (br.ready()) {
pw.println();
pw.append("\t\t").append(br.readLine());
}
} finally {
pw.flush();
throw new IOException(sw.toString());
}
}
}
示例12: getHTMLRepresentation
import java.io.StringWriter; //导入依赖的package包/类
/**
* Method getHTMLRepresentation
*
* @return The HTML Representation.
* @throws XMLSignatureException
*/
public String getHTMLRepresentation() throws XMLSignatureException {
if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) {
return HTMLPrefix + "<blink>no node set, sorry</blink>" + HTMLSuffix;
}
// get only a single node as anchor to fetch the owner document
Node n = this.xpathNodeSet.iterator().next();
this.doc = XMLUtils.getOwnerDocument(n);
try {
this.writer = new StringWriter();
this.canonicalizeXPathNodeSet(this.doc);
this.writer.close();
return this.writer.toString();
} catch (IOException ex) {
throw new XMLSignatureException("empty", ex);
} finally {
this.xpathNodeSet = null;
this.doc = null;
this.writer = null;
}
}
示例13: showException
import java.io.StringWriter; //导入依赖的package包/类
public static void showException(final Activity activity, Exception e, SimpleCallback callback) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Throwable cause = e.getCause();
if (cause!=null) {
cause.printStackTrace(pw);
} else {
e.printStackTrace(pw);
}
final TextView text = (TextView)activity.findViewById(R.id.txtDialogAction);
text.setTextSize(12);
String msg = e.toString() + "\n" + e.getMessage() + "\n" + sw.toString();
showAlert(activity, "Error", msg, callback);
}
示例14: compileFiles
import java.io.StringWriter; //导入依赖的package包/类
public static void compileFiles(File projectRoot, List<String> javaFiles) {
DiagnosticCollector diagnosticCollector = new DiagnosticCollector();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.ENGLISH, Charset.forName("utf-8"));
Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(javaFiles.toArray(new String[0]));
File outputFolder = new File(projectRoot, "bin");
if (!outputFolder.exists()) {
outputFolder.mkdir();
}
String[] options = new String[] { "-d", outputFolder.getAbsolutePath() , "-g", "-proc:none"};
final StringWriter output = new StringWriter();
CompilationTask task = compiler.getTask(output, fileManager, diagnosticCollector, Arrays.asList(options), null, javaFileObjects);
boolean result = task.call();
if (!result) {
throw new IllegalArgumentException(
"Compilation failed:\n" + output);
}
List list = diagnosticCollector.getDiagnostics();
for (Object object : list) {
Diagnostic d = (Diagnostic) object;
System.out.println(d.getMessage(Locale.ENGLISH));
}
}
示例15: getAllDataFromInputStream
import java.io.StringWriter; //导入依赖的package包/类
public static StringWriter getAllDataFromInputStream(InputStream is) throws IOException {
StringWriter writer = new StringWriter();
try {
while (is.available() > 0) {
byte[] buf = new byte[1024];
int len = is.read(buf);
String s = new String(buf, 0, len);
writer.append(s);
}
} catch (Exception e) {
return new StringWriter();
}
return writer;
}