Output to a file in java


 
Thread Tools Search this Thread
Top Forums Programming Output to a file in java
# 1  
Old 10-14-2009
Output to a file in java

I wanna remove element from xml file, when I run the following code I get the correct output when I'm outputing to console but when I'm trying to ouptup the same code to a file I get the same / original xml file without removed element, here is the code :

Code:
import java.io.*;

import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class RemoveBlock {

  static public void main(String[] arg) {
    try{
      String xmlFile = "Management.xml";
      File file = new File(xmlFile);
      String remElement = "Physical_Order_List_Array";
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tFormer = tFactory.newTransformer();
        Element element = (Element)doc.getElementsByTagName(remElement).item(0);
//        Remove the node
        element.getParentNode().removeChild(element);
//              Normalize the DOM tree to combine all adjacent nodes
        doc.normalize();
        Source source = new DOMSource(doc);
        Result dest = new StreamResult(System.out);
        tFormer.transform(source, dest);
       // System.out.println();
       // saveStringToFile("emir.xml", "dsds"); -> write method
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      System.err.println(e);
      System.exit(0);
    }
  }
}

The code above is working but when I want to change it to output to a file like : Result dest = new StreamResult(new File("foo.xml")); or Result dest = new StreamResult(new FileOutputStream("foo.xml")); its not working, any indications why ?

Thank you
# 2  
Old 10-14-2009
not entirely sure, but I think you can't transform a DOM Document into a stream result without serializing it first.

look at the docs for org.apache.xml.serializer.DOMSerializer;

here's some code fragments that may be helpful.

Code:
public static Serializer getSerializer()
	{
		Properties props = OutputPropertiesFactory.getDefaultMethodProperties("xml");
		ser = SerializerFactory.getSerializer(props);
		return ser;
	}

os = new ByteArrayOutputStream();
ros = new ByteArrayOutputStream();
getSerializer().setOutputStream(os);
DOMSerializer dser = getSerializer().asDOMSerializer();
dser.serialize(document);
is = new ByteArrayInputStream(os.toByteArray());
source = new StreamSource(is);
result = new StreamResult(ros);

# 3  
Old 10-15-2009
tnx for your answer .. I've writen removeallnodes method which goes trough every child of a element I wanna get rid of and it works now as it should
# 4  
Old 10-15-2009
Try XSL for deleting elements

Since your code does a transform anyway, consider using the following XSLT:
Code:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!-- Passthru for XML tags -->
<xsl:template match="*">
  <xsl:copy>
    <xsl:copy-of select="@*"/>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>
<xsl:template match="Physical_Order_List_Array"/>
</xsl:stylesheet>

This XSL removes the need for this code:
Code:
        Element element = (Element)doc.getElementsByTagName(remElement).item(0);
//        Remove the node
        element.getParentNode().removeChild(element);
//              Normalize the DOM tree to combine all adjacent nodes
        doc.normalize();

A bonus of the XSL approach is that you don't even have to write a Java program. On Linux run
Code:
xsltproc --output destination.xml prune.xsl source.xml

Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Supress java error output to shell

Hello, I know this isn't exactly a shell script question but I'm not sure where else to post it. I am running a java program out of a shell script. There are times when I get an error like, "java.lang.ArrayIndexOutOfBoundsException: 22 at blah, blah at blah, blah ... (3 Replies)
Discussion started by: LMHmedchem
3 Replies

2. Programming

Running java script from piped output

to run most other scripts through a pipe, something similar to the following is usually enough: cat script.sh | sh cat perl.pl | perl -- "<arguments" However, for javascript command line scripts, i cant seem to get this to work. Any ideas? cat hull.js #!/usr/bin/js ... (3 Replies)
Discussion started by: SkySmart
3 Replies

3. Shell Programming and Scripting

Reading output returned to OS from java program.

I am writing one shell script in which there is one Java program call. I want to stop execution of shell script ahead of java program if the java program returns 1 . How to read that value of java program from OS ? (3 Replies)
Discussion started by: ParthThakkar
3 Replies

4. AIX

Any file to differentiate JAVA JRE and JAVA JDK

Folks, Any idea of where can I find a specific file to differentiate JRE and Java JDK installed on AIX platform :cool: (3 Replies)
Discussion started by: dellcisco
3 Replies

5. Shell Programming and Scripting

Problem with call of Java Programm & return code handling & output to several streams.

Hello Everybody, thanks in advance for spending some time in my problem. My problem is this: I want to call a java-Programm out of my shell skript, check if die return code is right, and split the output to the normal output and into a file. The following code doesn't work right, because in... (2 Replies)
Discussion started by: danifunny
2 Replies

6. Shell Programming and Scripting

Logging Remote SSH command (cannot log a java output)

Hi all I'm creating a script that runs a few commands on some boxes and everything can be logged EXCEPT the java -version command, there doesn't seem to be any output... Can anyone help explain why this does not work? Do I need to do something extra to append the output from the java... (3 Replies)
Discussion started by: Keepcase
3 Replies

7. Shell Programming and Scripting

Dynamic output file generation using a input text file with predefined output format

Hi, I have two files , one file with data file with attributes that need to be sent to another file to generate a predefined format. Example: File.txt AP|{SSHA}VEEg42CNCghUnGhCVg== APVG3|{SSHA}XK|"password" AP3|{SSHA}XK|"This is test" .... etc --------- test.sh has... (1 Reply)
Discussion started by: hudson03051nh
1 Replies

8. UNIX for Dummies Questions & Answers

Interpreting java output stream as system commands in Solaris

Hi there again, Running Solaris 10 with built-in Java. Seems to compile and run fine. Problem is: Say I want to see contents of current directory. In a shell, I'd just write "ls" and it outputs the content. When I write a Java file, I have the following line: System.out.println("ls"); ... (1 Reply)
Discussion started by: EugeneG
1 Replies

9. UNIX for Dummies Questions & Answers

lslpp output for Java package

Hi , in the process of installing HBA's(IBM 6228's) for AIX 6F1 which was recently upgdared to 5.3 ML1 after the upgrade lppchk -v output displays the following. >lppchk -v lppchk: The following filesets need to be installed or corrected to bring the system to a consistent state: ... (1 Reply)
Discussion started by: Student37
1 Replies
Login or Register to Ask a Question