Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit6f8a16f

Browse files
committed
Refactor + Add Logging
1 parent2ee234a commit6f8a16f

File tree

7 files changed

+167
-181
lines changed

7 files changed

+167
-181
lines changed

‎.gitignore‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,6 @@ artifacts/
1515

1616
# Maven
1717
log/
18-
target/
18+
target/
19+
20+
examples/

‎README.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,19 @@
33
* Uses the traditional methodology to generate the xml (without a library), through
44
of nodes and tree structure.
55
* Can read ANY CSV File
6-
* Args are: Input file, output file, element node name and optionally, if you add -s program will read the csv
6+
* Args are:
7+
-[0] Input file
8+
-[1] Output file
9+
-[2] Element node name and optionally,
10+
-[3] -s parameter, if you add it, program will read the csv
711
as semicolon-separated values instead of comma-separated values.
12+
13+
Example of command to compile and run the program for comma-separated values:
14+
```
15+
javac CSV2XML.java
16+
java CSV2XML inputfilePath outputFilePath element -s
17+
```
18+
819
##Project test
920

1021
###CSV Input File
Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,59 @@
11
packagecom.codepressed.CSVtoXML;
22

3-
importorg.apache.commons.lang3.StringUtils;
3+
44
importorg.w3c.dom.Document;
55
importjavax.xml.parsers.ParserConfigurationException;
66
importjavax.xml.transform.TransformerException;
77
importjava.io.IOException;
88
importjava.util.ArrayList;
9+
importjava.util.List;
10+
importjava.util.logging.Level;
11+
importjava.util.logging.Logger;
12+
913

1014
publicclassMain {
15+
privatestaticfinalLoggerlogger =Logger.getLogger(Main.class.getName());
16+
1117
/**
1218
* Executes the CSV to XML conversion
1319
*
14-
* @param args Input file,outputfile,elementsnames and csv type.
15-
* @author Daniel Apesteguia Timoner
20+
* @param args[0] =Input file,[1] = Outputfile,[2] = Elementsnames, [3] = csv type.
21+
* @author Daniel Apesteguia Timoner (Codepressed)
1622
*/
1723
publicstaticvoidmain(String[]args) {
24+
1825
//Arg validator
1926
if (args.length ==0) {
20-
System.out.println("You didn't type any args.");
27+
logger.log(Level.SEVERE,"No args were specified.");
2128
System.exit(0);
2229
}
23-
//Vars Initialization
24-
StringcsvFile =args[0];
25-
StringxmlFile =args[1];
26-
StringelementName;
27-
StringcsvSplit =",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
28-
29-
try {
30-
elementName =args[2];
31-
}catch (ArrayIndexOutOfBoundsExceptione) {
32-
System.out.println("You didn't especify any element so we will fix 'element' as parental node.");
33-
elementName ="element";
34-
}
30+
//Vars Initialization
31+
StringcsvFile =args[0];
32+
StringxmlFile =args[1];
33+
StringelementName;
34+
StringcsvSplit =",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
3535

36-
try {
37-
if (args[3] =="-s")
38-
csvSplit =";(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
39-
}catch (ArrayIndexOutOfBoundsExceptione){
40-
}
36+
try {
37+
elementName =args[2];
38+
}catch (ArrayIndexOutOfBoundsExceptione) {
39+
logger.log(Level.INFO,"Since you didn't specify a element name, 'element' will be the parental node.");
40+
elementName ="element";
41+
}
4142

42-
try {
43-
ArrayList<String[]>elements;
44-
elements =newReader().CSVtoArrayList(csvFile,csvSplit);
45-
DocumentxmlDoc;
46-
xmlDoc =newXMLDoc().docBuilder(elements,elementName);
47-
XMLTransformer.transformDocToFile(xmlDoc,xmlFile);
48-
}catch (IOExceptione) {
49-
e.printStackTrace();
50-
System.out.println("File wasn't found, error: " +e);
51-
}catch (TransformerExceptione) {
52-
System.out.println("Transformer error: " +e);
53-
}catch (ParserConfigurationExceptione) {
54-
System.out.println("Configuration error: " +e);
55-
}
43+
try {
44+
if (args[3] =="-s")
45+
csvSplit =";(?=([^\"]*\"[^\"]*\")*[^\"]*$)";
46+
}catch (ArrayIndexOutOfBoundsExceptione){
47+
}
48+
49+
List<String[]>elements;
50+
elements =XMLutils.readCsvFile(csvFile,csvSplit);
51+
DocumentxmlDoc;
52+
xmlDoc =XMLutils.createXmlDocument(elements,elementName);
53+
XMLutils.writeXmlDocumentToFile(xmlDoc,xmlFile);
54+
}
5655
}
57-
}
56+
57+
58+
5859

‎src/main/java/com/codepressed/CSVtoXML/Reader.java‎

Lines changed: 0 additions & 36 deletions
This file was deleted.

‎src/main/java/com/codepressed/CSVtoXML/XMLDoc.java‎

Lines changed: 0 additions & 71 deletions
This file was deleted.

‎src/main/java/com/codepressed/CSVtoXML/XMLTransformer.java‎

Lines changed: 0 additions & 36 deletions
This file was deleted.
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
packagecom.codepressed.CSVtoXML;
2+
3+
importorg.w3c.dom.Document;
4+
importorg.w3c.dom.Element;
5+
importorg.w3c.dom.Text;
6+
7+
importjavax.xml.parsers.DocumentBuilder;
8+
importjavax.xml.parsers.DocumentBuilderFactory;
9+
importjavax.xml.parsers.ParserConfigurationException;
10+
importjavax.xml.transform.OutputKeys;
11+
importjavax.xml.transform.Transformer;
12+
importjavax.xml.transform.TransformerException;
13+
importjavax.xml.transform.TransformerFactory;
14+
importjavax.xml.transform.dom.DOMSource;
15+
importjavax.xml.transform.stream.StreamResult;
16+
importjava.io.BufferedReader;
17+
importjava.io.File;
18+
importjava.io.FileOutputStream;
19+
importjava.io.IOException;
20+
importjava.nio.file.Files;
21+
importjava.nio.file.Paths;
22+
importjava.util.ArrayList;
23+
importjava.util.List;
24+
importjava.util.logging.Level;
25+
importjava.util.logging.Logger;
26+
27+
publicclassXMLutils {
28+
29+
privatestaticfinalLoggerlogger =Logger.getLogger(XMLutils.class.getName());
30+
31+
publicstaticbooleanwriteXmlDocumentToFile(DocumentxmlDoc,StringxmlFilePath) {
32+
try {
33+
TransformerFactoryxmlTransformerFactory =TransformerFactory.newInstance();
34+
TransformerxmlTransformer =xmlTransformerFactory.newTransformer();
35+
xmlTransformer.setOutputProperty(OutputKeys.INDENT,"yes");
36+
xmlTransformer.setOutputProperty(OutputKeys.METHOD,"xml");
37+
xmlTransformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
38+
xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
39+
40+
try (FileOutputStreamoutputStream =newFileOutputStream(newFile(xmlFilePath))) {
41+
xmlTransformer.transform(newDOMSource(xmlDoc),newStreamResult(outputStream));
42+
}
43+
returntrue;
44+
}catch (TransformerException |IOExceptione) {
45+
logger.log(Level.SEVERE,"Error writing xml document to file",e);
46+
returnfalse;
47+
}
48+
}
49+
50+
publicstaticDocumentcreateXmlDocument(List<String[]>XMLelements,StringelementName) {
51+
if (elementName ==null) {
52+
elementName ="element";
53+
}
54+
55+
try {
56+
DocumentBuilderFactoryxmlFactory =DocumentBuilderFactory.newInstance();
57+
DocumentBuilderxmlBuilder =xmlFactory.newDocumentBuilder();
58+
DocumentxmlDoc =xmlBuilder.newDocument();
59+
60+
ElementrootElement =xmlDoc.createElement("root");
61+
xmlDoc.appendChild(rootElement);
62+
ElementmainElement =xmlDoc.createElement(elementName +"s");
63+
rootElement.appendChild(mainElement);
64+
65+
booleanheaderDefined =false;
66+
String[]header =newString[XMLelements.size()];
67+
68+
for (String[]node :XMLelements) {
69+
if (headerDefined) {
70+
ElementnodesElements =xmlDoc.createElement(elementName);
71+
mainElement.appendChild(nodesElements);
72+
73+
for (intj =0;j <node.length;j++) {
74+
node[j] =node[j].replaceAll("\"","").trim();
75+
ElementnodesValues =xmlDoc.createElement(header[j]);
76+
nodesElements.appendChild(nodesValues);
77+
TextnodeTxt =xmlDoc.createTextNode(node[j]);
78+
nodesValues.appendChild(nodeTxt);
79+
}
80+
}else {
81+
header =node;
82+
for (intj =0;j <node.length;j++) {
83+
header[j] =header[j].replaceAll("[^a-zA-Z0-9]","");
84+
try {
85+
Integer.parseInt(header[j]);
86+
header[j] ="node" +header[j];
87+
}catch (NumberFormatExceptione) {
88+
}
89+
}
90+
headerDefined =true;
91+
}
92+
}
93+
returnxmlDoc;
94+
}catch (ParserConfigurationExceptione) {
95+
logger.log(Level.SEVERE,"Error creating the xml document",e);
96+
returnnull;
97+
}
98+
}
99+
100+
publicstaticList<String[]>readCsvFile(StringcsvFilePath,Stringseparator) {
101+
List<String[]>elements =newArrayList<>();
102+
103+
try (BufferedReaderreader =Files.newBufferedReader(Paths.get(csvFilePath))) {
104+
Stringline;
105+
while ((line =reader.readLine()) !=null) {
106+
String[]nodes =line.split(separator);
107+
elements.add(nodes);
108+
}
109+
}catch(IOExceptione){
110+
logger.log(Level.SEVERE,"Error reading the csv file",e);
111+
}
112+
returnelements;
113+
}
114+
115+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp