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.
Related
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
package demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.poi.openxml4j.opc.*;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class DocxToPdf {
public static void main(String[] args){
try
{
String inputFile = "F:\\MY WORK\\CollectionPractice\\WebContent\\APCR1.docx";
String outputFile = "F:\\MY WORK\\CollectionPractice\\WebContent\\APCR1.pdf";
System.out.println("inputFile:" + inputFile + ",outputFile:" + outputFile);
FileInputStream in = new FileInputStream(inputFile);
XWPFDocument document = new XWPFDocument(in);
File outFile = new File(outputFile);
OutputStream out = new FileOutputStream(outFile);
PdfOptions options = null;
PdfConverter.getInstance().convert(document, out, options);
} catch (Exception e) {
e.printStackTrace();
}
}
}
when i run this code an error occur like these and i have used following jar files also.
error:
java.lang.NoSuchMethodError: org.apache.poi.POIXMLDocumentPart.getPackageRelationship()Lorg/apache/poi/openxml4j/opc/PackageRelationship;
jars:
List of jar files
You likely have jar-versions of POI mixed up. The error indicates that the class that was loaded did not have a method that the calling class saw during compilation, so you have a different version of POI in your classpath.
See "Component Map" at https://poi.apache.org/overview.html for the different components that are included and which jars they end up, make sure you only have one of these jars in your classpath, not multiple different versions.
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/
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Applying XSLT v. 2 on XML
I have a Directory structure with XML files. I am having an XSLT 1.0 which I am applying on all these files and generating new XML files for each. I had written code in JAVA. But my problem is I am not able to put output files at a separate output folder having same structure as one from which I am taking my input XML file. For Example if I have a root directory Home with two folders Folder1 and Folder2. Each Folder1 & Folder2 has number of XML files. So when I convert my XML files present in these folders so the output files so generated should go in separate folder having same structure.
Here is the Java code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class XMLwithXSLT {
public static void main(String[] args) throws FileNotFoundException,
TransformerConfigurationException, TransformerException {
File dir = new File("Input Directory Root Path Here");
listFilesInDirectory(dir);
}
public static void listFilesInDirectory(File dir) throws FileNotFoundException,
TransformerException {
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
System.out.println(f.getName());
listFilesInDirectory(f);
} else {
System.out.println(f.getName());
OutputXml(f);
}
}
}
public static void OutputXml(File in) throws FileNotFoundException,
TransformerException{
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xslDoc = new StreamSource("backup.xslt");
Source xmlDoc = new StreamSource(in.getPath()) ;
System.out.print(in.getName() + "/n");
String outputFileName = in.getName();
System.out.print(outputFileName );
OutputStream htmlFile;
htmlFile = new FileOutputStream(outputFileName);
Transformer transformer = tFactory.newTransformer(xslDoc);
transformer.transform(xmlDoc, new StreamResult(htmlFile));
}
}
So can anyone help me as how I can specify the output path for the generated new file? Also how I can generate a output files in the same directory format as input?
You should add the path to your output dir. For example:
String outputFileName = "c:\\tmp\\xmloutput\\" + in.getName();
So basicaly, loop your input files and take over subdir and file name. See if it exists in your output directory and if not create it. And if zo, then name your outputFileName this way.
What i got from your question is , There are two folders Folder1 and Folder2. Folder1 Have some XML file and Folder2 have some XML file. Lets consider you have got the output for all xml file present in Folder1 to HTML format. and Now you want those HTML files to be present in a folder called Folder1 some where in your system(or lets consider the temp folder of the system).and same for all the XML files present in Folder2.
If you want this kind of output then update the code with following
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class XMLwithXSLT {
static String pathRequiredForFile=null;
static String tempfolder=System.getProperty("java.io.tmpdir");
public static void main(String[] args) throws FileNotFoundException,
TransformerConfigurationException, TransformerException {
File dir = new File("Input Directory Root Path Here");
listFilesInDirectory(dir);
}
public static void listFilesInDirectory(File dir) throws FileNotFoundException,
TransformerException {
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
pathRequiredForFile=f.getName();
listFilesInDirectory(f);
} else {
System.out.println(f.getName());
File path=new File(tempfolder+"//"+pathRequiredForFile);
path.mkdir();
OutputXml(f,path.getAbsolutePath());
}
}
}
}
public static void OutputXml(File in,String saveFileInPath) throws FileNotFoundException,
TransformerException{
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xslDoc = new StreamSource("backup.xslt");
Source xmlDoc = new StreamSource(in.getPath()) ;
System.out.print(in.getName() + "/n");
String outputFileName = in.getName().split("\\.")[0];
System.out.println(outputFileName );
OutputStream htmlFile;
htmlFile = new FileOutputStream(saveFileInPath+"//"+outputFileName+".html");
Transformer transformer = tFactory.newTransformer(xslDoc);
transformer.transform(xmlDoc, new StreamResult(htmlFile));
}
}