StringWriter write to folder - java

Good Afternoon. I want to use the StringWriter to write the new file to a network folder. Can anyone give me some examples using the code below on how to do this? It's my first time working with the StringWriter class.
public static final void newOutput(Document xml) throws Exception {
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter out = new StringWriter();
tf.transform(new DOMSource(xml), new StreamResult(out));
/*
* need to update to write to folder
*/
System.out.println(out.toString());
}
}

public static final void newOutput(Document xml) throws Exception {
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(xml);
// Use StreamResult to write to a file to current directory
StreamResult out = new StreamResult(new File("test.txt"));
// to print to console
// StreamResult out = new StreamResult(System.out);
tf.transform(source, out);
/*
* console output is redirected to SRC folder to check format
* need to update to write to folder
*/
System.out.println(out.toString());
}

Related

Saving DOMSource object created into a folder in SFTP Server in Java

I need to save the newly created DOMSource object as new XML file into a folder inside the SFTP server (not transferring a file from local computer into SFTP).
Here is the code
public void save(String xmlFilePath, Document document) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
Transformer transformer;
try {
transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(xmlFilePath));
transformer.transform(domSource,streamResult);
} catch (TransformerException | NullPointerException e) {
e.printStackTrace();
}
}
Use JSch SSH/SFTP library.
Afaik, it's the most widely used SFTP library for Java
It supports uploading data from streams.
I assume that its ChannelSftp.put overload that returns OutputStream can be hooked to your StreamResult (instead of the File).
StreamResult streamResult =
new StreamResult(channelSftp.put("/sftp/path/file.zml"));

Strange characters appended at beginning of file in Hadoop

Whenever I create a new file in Hadoop using Java, and write the contents, special characters are appended at the beginning of the file. Is there a way to eliminate? Below is the code
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
String extractedXML = writer.getBuffer().toString().replaceAll("\\r$", "");
FSDataOutputStream fin = fs.create("/filelocation/input.txt");
fin.writeUTF(extractedXML);
fin.close();
$ hadoop fs -cat /filelocation/input.txt|head -5
)â–’hello world
input1
hello again
hello
welcome again
It worked for me, just by replacing the below lines
FSDataOutputStream fin = fs.create("/filelocation/input.txt");
fin.writeUTF(extractedXML);
fin.close();
with below code :
OutputStream os = fs.create( "/filelocation/input.txt", new Progressable() {
public void progress() {
}
});
BufferedWriter br = new BufferedWriter( new OutputStreamWriter( os, "UTF-8" ) );
br.write(extractedXML);
br.close();

Print the syncml payload to a xml file

I want to print the syncml payload in a xml file before using it. Is there a method in java to print the syncml payload into a xml file or a way to check the payload?
Solved by converting it to a string. (able to find more details from --> http://www.theserverside.com/news/thread.tss?thread_id=26060)
public void printXML(Document request){
try
{
DOMSource domSource = new DOMSource(request);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
String checkpayload = writer.toString();
System.out.print(checkpayload);
}
catch(TransformerException ex)
{
ex.printStackTrace();
}
}

Reading Transformer result line by line (Java)

I'm using Transformer to prettify and to insert indentation to an XML which is originally one big line.
Here is my code:
BufferedWriter br = null;
Source xmlInput = new StreamSource(inputSR);
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 2);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
How can I write the xmlOutput to a file, line by line (without loading the whole string to the memory)?
Instead of a StringWriter, use a FileOutputStream:
StreamResult xmlOutput = new StreamResult(new FileOutputStream("output.xml"))
This will write incrementally to the file. It won't necessarily write line-by-line (lines don't mean much in XML), but I can't see why you would want that.

Indent XML made with Transformer [duplicate]

This question already has answers here:
Pretty-printing output from javax.xml.transform.Transformer with only standard java api (Indentation and Doctype positioning)
(4 answers)
Closed 5 years ago.
I am trying to create XML from Java and am having problems with indenting. In the following code you can see OutputKeys.INDENT set to yes...
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
//print xml
System.out.println(xmlString);
but it seems to have no affect, the output is:
<dataset id="1"><br>
<path></path><br>
<session id="1"><br>
<method><br>
<timestamp>a timestamp</timestamp><br>
<signiture><br>
<classPath></classPath><br>
<name>methodName</name><br>
<declarationType>String</declarationType><br>
<parameters><br>
<parameter>String</parameter><br>
<parameter>int</parameter><br>
</parameters><br>
</signiture><br>
<arguments><br>
<argument>SomeValue</argument><br>
<argument>AnotherValue</argument><br>
</arguments><br>
<return>ReturnValue</return><br>
</method><br>
</session><br>
</dataset><br>
Try to set indent-amount, AFAIK the default is 0.
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4")
Document doc;
.....
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc), new StreamResult(new File("filename.xml")));
transformer.transform(new DOMSource(doc), new StreamResult(System.out));

Categories