Save the exported CSV file via Java - java

I have managed to export a CSV file using JAVA. Now, I want those CSV files to be saved because I noticed that if I do not manually save them, I cannot use my CSV files to connect with other programs and do things with them. Please take a look, and help me out. Thank you !!!
package edi.converter.main;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import edi.converter.outbound.sqlserver.OutboundProcess;
public class MainAppConverter {
public static void main(String[] args) throws Exception {
Result outputTarget = new StreamResult(new File("C:\\Users\\Khoa S Tran\\Desktop\\out.csv"));
Result outputTarget1 = new StreamResult(new File("C:\\Users\\Khoa S Tran\\Desktop\\out1.csv"));
File stylesheet = new File("C:\\Users\\Khoa S Tran\\Desktop\\style.xsl");
File xmlSource = new File("C:\\Users\\Khoa S Tran\\Desktop\\data.xml");
File xmlSource1 = new File("C:\\Users\\Khoa S Tran\\Desktop\\data1.xml");
// it is noted that it is impossible/challlenging to combine xml files then export them to one csv
//suggestion will be concatenate multiple csv files together
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlSource);
Document document1 = builder.parse(xmlSource1);
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);
Source source = new DOMSource(document);
Source source1 = new DOMSource(document1);
transformer.transform(source, outputTarget);
//OutboundProcess.trytoExportSQL();
transformer.transform(source1, outputTarget1);
}
}
Bottom line is I have 2 XML files, I want to read them, combine them together, and export them to 1 single CSV file.
In case you might wonder where I can find the source code for concatenating 2 CSV's: How to merge multiple csv files into one in Java

Related

xsl-fo transformation much slower with Java 11 instead of 1.8

After updating my program to Java 11, the transformations of an XML using xsl-fo (AWT renderer) have become much slower:
Java 11: 90 seconds
Java 1.8: 5 seconds
I've not tried it with Java 9 or 10.
There was no code and no stylesheet change between the run with Java 11 and 1.8.
I'm using org.apache.xmlgraphics:fop in version 2.3.
Also with Saxon-HE 9.9.1-5 (instead of Xalan) there was unfortunately no performance improvement.
Via profiling and debugging it looks like the code line 284 in the class org.apache.fop.layoutmgr.table.TableContentLayoutManager consumes the time:
nextRowGroupElems = rowGroupLM.getNextKnuthElements(context, alignment, bodyType);
So the culprit is Apache FOP using AWT. Using MIME_PDF instead of MIME_FOP_AWT_PREVIEW is much faster: 5 seconds vs 90 seconds.
The profiler (JProfiler) shows java.awt.EventDispatchThread as hot spot for Java 11. So maybe it is an AWT problem.
The relevant Code to reproduce:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.FopConfParser;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.FopFactoryBuilder;
import org.apache.fop.apps.MimeConstants;
import org.springframework.core.io.ClassPathResource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class MyTransform {
public static void main(String[] args) throws Exception {
Document xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream("my_xml.xml"));
Document xslDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("my_xsl.xsl"));
Transformer transformer = TransformerFactory.newInstance().newTransformer(new DOMSource(xslDoc));
DOMSource xmlDomSource = new DOMSource(xmlDoc);
DOMResult domResult = new DOMResult();
transformer.transform(xmlDomSource, domResult);
Source src = new DOMSource(domResult.getNode());
Result res = new SAXResult(createFopFactory().newFop(MimeConstants.MIME_FOP_AWT_PREVIEW, getDisplayAgent()).getDefaultHandler());
TransformerFactory factory = javax.xml.transform.TransformerFactory.newInstance();
transformer = factory.newTransformer();
transformer.transform(src, res);
transformer.transform(src, res); // took with Java 11 90 seconds and with Java 1.8 5 seconds
}
private static FopFactory createFopFactory() throws SAXException, IOException {
ClassPathResource resource = new ClassPathResource("fop_configuration.xml");
FopConfParser parser = new FopConfParser(resource.getInputStream(), resource.getURI()); //parsing configuration
FopFactoryBuilder builder = parser.getFopFactoryBuilder(); //building the factory with the user options
return builder.build();
}
private static FOUserAgent getDisplayAgent() throws SAXException, IOException {
FopFactory fopFactory = createFopFactory();
FOUserAgent displayAgent = fopFactory.newFOUserAgent();
MyAWTRendererMaker maker = new MyAWTRendererMaker();
displayAgent.getRendererFactory().addRendererMaker(maker);
MyAWTRenderer displayRenderer = new MyAWTRenderer(displayAgent);
displayAgent.setRendererOverride(displayRenderer);
return displayAgent;
}
}
I solved the problem by first generating a PDF and then displaying it in a dialog box of ICEpdf instead of Apache FOP. It seems that using the output format MIME_FOP_AWT_PREVIEW causes the problems, instead I now use MIME_PDF.

Java: Append to XML File [duplicate]

This question already has answers here:
Modify the content of a file using Java
(6 answers)
Closed 5 years ago.
I have the below code that writes to an xml file, the problem that I am having is that it creates a new file every time i write to it and overwrites the other data saved in the file. I am looking for a solution that would append to the existing file instead. How do I modify this code to append to the file each time instead of overwrite? Also, I am using the netbeans IDE to run this program.
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class WriteXMLFile {
public static void main() throws ParserConfigurationException,SAXException,Exception
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();//
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();//
Document doc = docBuilder.newDocument();// this is difrent
Element rootElement = doc.createElement("Contacts");//
doc.appendChild(rootElement); // this is difrent
// staff elements
Element Contact1 = doc.createElement("Contact1");
rootElement.appendChild(Contact1);
// set attribute to staff element
Contact1.setAttribute("id","1");
// firstname elements
Element firstname = doc.createElement("Name");
firstname.appendChild(doc.createTextNode(EmailFrame.name.getText()));
Contact1.appendChild(firstname);
//Email Element
Element email = doc.createElement("Email");
email.appendChild(doc.createTextNode(EmailFrame.email.getText()));
Contact1.appendChild(email);
// phone element
Element phone= doc.createElement("Phone");
phone.appendChild(doc.createTextNode(EmailFrame.phone.getText()));
Contact1.appendChild(phone);
//id element
Element id = doc.createElement("ID");
id.appendChild(doc.createTextNode(EmailFrame.id.getText()));
Contact1.appendChild(id);
try{
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:/Users/steve/Desktop/xmlemail/Email.xml"));
transformer.transform(source, result);
System.out.println("File saved!");
}
catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
What you need to do is read the contents of the xml file into an object first before writing, then append your new content to your object then write your object to the xml file
Look at this resource for reading an xml file it should help
https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

Java Translate XML into HTML using XSL

I used JAXB to create a very complicated .xml file which I saved on the drive. I also manually made an .xsl file which is my template.
How do I now programmatically use the above two to create an html output file ?
I tried various things and maybe I'm just tired but I can't even successfully open the .xml file into a Document.
Does someone have a working example ? I would greatly appreciate it! Thanks :)
I tried various things, including the official code examples but I can't find a working example. Nothing but null pointer exceptions. :(
The smallest working example I can give you:
import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class UseXMLToHTML {
public static void main(String[] args) throws TransformerException {
StreamResult result = new StreamResult(new File("output.html"));
StreamSource source = new StreamSource(new File("input.xml"));
StreamSource xslt = new StreamSource(new File("transform.xslt"));
Transformer transformer = TransformerFactory.newInstance().newTransformer(xslt);
transformer.transform(source, result);
}
}
This would probably do the trick;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
public class TestMain {
public static void main(String[] args) throws IOException, URISyntaxException, TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(new File("transform.xslt"));
Transformer transformer = factory.newTransformer(xslt);
Source text = new StreamSource(new File("input.xml"));
transformer.transform(text, new StreamResult(new File("output.xml")));
}
}
Consider trying out stuff from these urls:
http://www.w3schools.com/xsl/tryxslt.asp?xmlfile=cdcatalog&xsltfile=cdcatalog
http://www.w3schools.com/xsl/tryxslt_result.asp?xmlfile=cdcatalog&xsltfile=cdcatalog

Jar FileNotFoundException caused by write to a xml File

I am trying to write to a XML file. It runs correctly in eclipse. The file is located at ca/ism/wen/domain folder (together with my user.java). However, it is throws FileNotFoundException when I run the exported runnable jar file. Is there way to write to an xml file in the jar file? Following is my code.
package ca.ism.wen.utils;
import java.io.File;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import ca.ism.wen.domain.User;
/**
* Load XML file
*
*/
public class XmlFactory {
private static Document dom;
//private static File file = new File(User.class.getResource("UserRDP.xml").getPath());
private static InputStream filei = User.class.getResourceAsStream("UserRDP.xml");
private static File fileo = new File(User.class.getResource("UserRDP.xml").getPath());
static {
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(filei);
} catch (Exception e){
e.printStackTrace();
}
}
public static Document getDom(){
return dom;
}
public static void saveDom(){
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
DOMSource ds = new DOMSource(dom);
StreamResult sr = new StreamResult(fileo);
trans.transform(ds, sr);
} catch (Exception e){
throw new RuntimeException(e.getMessage(),e);
}
}
}
If I have to put my XML file externally somewhere, I want to get a runnable file and put it in a folder under my whole project (just like normal software), cause it may be deployed to other person's machine later. Is that possible?
I believe you need to provide an implementation for javax.xml.parsers.DocumentBuilderFactory as a third party library to your classpath as per the javadoc.
Try
new File(User.class.getResource("UserRDP.xml").toURI());
The appropriate constructor of the File should be used to locate the resource. This approach only works with exploded jar. You cannot write to a jar, however you can read from it using jar protocol.

Need to use saxon for transforming html to xml using xslt

I am converting html to xml using xslt1.0. I want to migrate to xslt2.0 for some built-in functions. Currently my transformation code is like,
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
and method for conversion is
public static String convert(String inputHtml, String xsl) throws Exception {
File xsltFile = new File(xsl);
InputStream is = new ByteArrayInputStream(inputHtml.getBytes("UTF-8"));
javax.xml.transform.Source xmlSource = new javax.xml.transform.stream.StreamSource(is);
javax.xml.transform.Source xsltSource = new javax.xml.transform.stream.StreamSource(xsltFile);
StringWriter sw = new StringWriter();
javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult(sw);
javax.xml.transform.TransformerFactory transFact = javax.xml.transform.TransformerFactory.newInstance();
javax.xml.transform.Transformer trans = transFact.newTransformer(xsltSource);
trans.transform(xmlSource, result);
return sw.getBuffer().toString();
}
How to write for saxon processor?. Thanks in advance
The Java code doesn't need to change: if Saxon9.3 is on the classpath, it should load it and use it automatically. But if you want to be 100% confident that Saxon gets loaded (which is probably a good idea if the code uses XSLT 2.0 or Saxon extensions) then change the line
TransformerFactory transFact javax.xml.transform.TransformerFactory.newInstance();
to
TransformerFactory transFact = new net.sf.saxon.TransformerFactoryImpl();

Categories

Resources