How to write xml into a file using MarkupBuilder - java

I created an xml using MarkupBuilder in groovy but how do i write it into a xml file in my project dir E:\tomcat 5.5\webapps\csm\include\xml
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
String[] splitted
xml.rows()
{ for(int i=0;i<lines.length-1;i++){
row()
{
for(int j=0;j<lines[i].length();j++)
{
splitted= lines[i].split(',');
}
name(splitted[0])
email(splitted[1])
}
}
}
here println writer.toString() prints my whole xml content but i need it in a file in my tomcat project's xml directory

Not to take away from the correct answers above, but you can make your code much more Groovy:
new File( "${System.properties['catalina.base']}/webapps/csm/include/xml/yourfile.xml" ).withWriter { writer ->
def xml = new MarkupBuilder( writer )
xml.rows {
lines.each { line ->
row {
def splitted = line.split( ',' )
name( splitted[0] )
email( splitted[1] )
}
}
}
}

Instead of using a StringWriter, use a FileWriter. Also use system property catalina.base to get the Tomcat homepath.
def writer = new FileWriter(new File(System.getProperty("catalina.base") + "/webapps/csm/include/xml/yourfile.xml"))
Note however that it's not the best place to save your runtime generated files. They will be deleted every time you redeploy your .war file.

How about:
new File('E:\tomcat 5.5\webapps\csm\include\xml\Foo.xml') << writer.toString()
Not sure if you need to double escape \\ file path on windoze...

Instead of using a StringWriter i used FileWriter
and as for the the path i did
def writer = new FileWriter("../webapps/csm/include/xml/data.xml" )
Finally this works :)

//class writer to write file
def writer = new StringWriter();
//builder xml
def xmlCreated = new MarkupBuilder(writer);
//file where will be write the xml
def fileXmlOut = new File("C:\\Users\\example\\Desktop\\example\\test.xml");
//method MarkupBuilder to xml
xmlCreated.mkp.xmlDeclaration(version: "1.0", encoding: "utf-8");
xmlCreated.playlist() {
list() {
//xml = your file xml parse
name xml.list.name.text()
}
eventlist () {
event(type: example.eventlist.#type)
}
}
//writing xml in file
fileXmlOut << writer.toString();

Related

How to create new column from CSVWriter in Java

I have a problem. I want to create a new CSV file from CSVWriter and my whole Array is set into the one cell.
This is my java code:
StringWriter s = new StringWriter();
#SuppressWarnings("deprecation")
CSVWriter writer = new CSVWriter(s, '\t');
String[] entries = new String[3];
entries[0] = "Test";
entries[1] = "Test";
writer.writeNext(entries);
writer.close();
String finalString = s.toString();
System.out.println(finalString);
I get the output like this: "first" "second" "third"
and my CSV is :
but I want to be like this:
Your code is OK, the problem is you open the CSV file by Excel with default settings.
If you open the CSV file with Notepad, it will look like this:
"Test" "Test"
And if you still want to open it with Excel, you are supposed to open it by following steps:
Create a new sheet.
Select Data > From Text File.
Select file (write.csv) to be imported.
Click Finish.

Groovy script xml parser for multiple files

Hi my groovy script strips out an xml tag from a file and writes to a file.
import org.apache.commons.lang.RandomStringUtils
import groovy.util.XmlSlurper
inputFile = 'C:\\sample.xml'
outputFile = 'C:\\ouput.txt'
XMLTag='Details'
fileContents = new File(inputFile).getText('UTF-8')
def xmlFile=new XmlSlurper().parseText(fileContents)
def myPayload= new String(xmlFile.'**'.find{node-> node.name() == XMLTag} *.text().toString())
file = new File(outputFile)
w = file.newWriter()
w << myPayload.substring(1, myPayload.length()-1)
w.close()
My question is how do I write it so the it goes through an entire directory and performs it on multiple xml files and creates multiple output as at the moment it is hard coded. ('C:\sample.xml' and 'C:\ouput.txt')
Thanks
Leon
First, I would recommend that you take what you have and put it into a single function; it's good coding practrice and improves readabililty.
Now to executing the function on each xml file in a directory, you can use groovy's File.eachFileMatch(). For example, if you want to run it on each xml file in the current directory, you could do:
import org.apache.commons.lang.RandomStringUtils
import groovy.util.XmlSlurper
import static groovy.io.FileType.*
void stripTag(File inputFile, String outputFile) {
def XMLTag='Details'
fileContents = inputFile.getText('UTF-8')
def xmlFile=new XmlSlurper().parseText(fileContents)
def myPayload= new String(xmlFile.'**'.find{node-> node.name() == XMLTag}*.text().toString())
def file = new File(outputFile)
w = file.newWriter()
w << myPayload.substring(1, myPayload.length()-1)
w.close()
}
// This will match all files in the current directory with the file extension .xml
new File(".").eachFileMatch(FILES, ~/.*\.xml/) { File input ->
// Set the output file name to be <file_name>_out.txt
// Change this as you need
stripTag(input, input.name + "_out.txt")
}
If you want to, you can add reading in the directory from the command line as well.

Create directory/directories in Eclipse with java.io.File

I tried to make it as easy as possible.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
mkdir() and mkdirs() return both false °_°. Both work (create directory) if i use double backslash \\ (like "\\non_existing_dir\\someDir" BUT:
if I do .toURI() after that I receive: file:/Users/MyName/Desktop/%5Cnon_existing_dir%5CsomeDir/
if I do .getPath() i receive: \non_existing_dir\someDir
if I do .getCanonicalPath() I receive: /Users/MyName/Desktop/\non_existing_dir\someDir
So i want to have instead this results:
with .toURI() receiving: file:/Users/MyName/Desktop/non_existing_dir/someDir/
with .getPath() receiving: /non_existing_dir/someDir
and with .getCanonicalPath() receiving: /Users/MyName/Desktop/non_existing_dir/someDir
Thanks in advance to everyone.
If non_existing_dir does not exists, you can check getParentFile() and create it with mkdir().
Also avoid problems between OS with File.separator.
String filename = "non_existing_dir" + File.separator + "someDir";
File f = new File(filename);
if (!f.exists()) {
if (!f.getParentFile().exists()) {
// make the dir
f.getParentFile().mkdir();
}
f.mkdir();
}

Java / Groovy&Grails File write

I have tried different ways to write a string to a file.
File file = new File(eventPath)
file.withWriterAppend { it << xmlDocument }
OR
file << xmlDocument
In this way, the string when the file size reaches 1kb is interrupted.
If I do this way (as explained here: java: write to xml file)
File file = new File("foo")
if (file.exists()) {
assert file.delete()
assert file.createNewFile()
}
boolean append = true
FileWriter fileWriter = new FileWriter(file, append)
BufferedWriter buffWriter = new BufferedWriter(fileWriter)
100.times { buffWriter.write "foo" }
buffWriter.flush()
buffWriter.close()
Happens that the string gets repeated.
How can I use the first method without have limit on string size? Thanks
Does:
new File(eventPath).withWriterAppend { it.writeLine xmlDocument }
work?

Java - How to create a file in a directory using relative Path

I want to create a file in a new directory using the relative path. Creating the directory "tmp" is easy enough.
However, when I create the file, it is just located in the current directory not the new one. The code line is below.
File tempfile = new File("tempfile.txt");
Have tried this also:
File tempfile = new File("\\user.dir\\tmp\\tempfile.txt");
Clearly I'm misunderstanding how this method works. Your assistance is greatly appreciated.
EDIT: added currently used code line as well as the one I think might work for a relative path to clear up confusion.
File dir = new File("tmp/test");
dir.mkdirs();
File tmp = new File(dir, "tmp.txt");
tmp.createNewFile();
BTW: For testing use #Rule and TemporaryFolder class to create temp files or folders
You can create paths relative to a directory with the constructors that take two arguments: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
For example:
File tempfile = new File("user.dir/tmp", "tempfile.txt");
By the way, the backslash "\" can be used only on Windows. In almost all cases you can use the portable forward slash "/".
String routePath = this.getClass().getClassLoader().getResource(File.separator).getPath();
System.out.println(routePath);
/*for finding the path*/
String newLine = System.getProperty("line.separator");
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(routePath+File.separator+".."+File.separator+"backup.txt"), true));
/*file name is backup.txt and this is working.*/
Let say you have "Local-Storage" on your project folder and you want to put a text or whatever file using file write.
File file = new File(dir,fileName ); //KEY IS DIR ex."./local-storage/" and fileName='comp.html'
// if file doesnt exists, then create it
if ( ! file.exists( ) )
{
file.createNewFile( );
}
FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
BufferedWriter bw = new BufferedWriter( fw );
bw.write( text );

Categories

Resources