Reading an XML file and write the contents to another xml file in java

Hi,
I am new to xml parsing.My requirement is that I am getting a message (xml) using ibm MQ in the ByteArrayInputStream format.I have to read this xml message and write to another file.
I am creating a POC for this.
First I used simple reading and writing concept but the output is "java.io.FileInputStream@3e25a5 "
Sample xml file
- <Client>
<ClientId>1234</ClientId>
<ClientName>STechnology</ClientName>
<DTU_ID>567</DTU_ID>
<ClientStatus>ACTIVE</ClientStatus>
- <LEAccount>
<ClientLE>678989</ClientLE>
<LEId>56743</LEId>
- <Account>
<AccountNumber>9876543678</AccountNumber>
</Account>
</LEAccount>
- <Service>
<Cindicator>Y2Y</Cindicator>
<PrefCode>980</PrefCode>
<BSCode>876</BSCode>
<MandatoryContent>MSP</MandatoryContent>
</Service>
</Client>
code:
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteArrayInputStreamToXml {
     public static void main(String srg[]) throws IOException{
          InputStream inputStream= new FileInputStream("C:\\soft\\test2\\sample1.xml");
          byte currentXMLBytes[] = inputStream.toString().getBytes();
          ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
          OutputStream out = new FileOutputStream("C:\\soft\\test\\data.xml");
          int read=0;
          byte[] bytes = new byte[1024];
          while((read = byteArrayInputStream.read(bytes))!= -1){
          out.write(bytes, 0, read);
          out.write( '\n' );
          inputStream.close();
          out.flush();
          out.close();
          System.out.println("New file created!");
Please suggest me how can I use DOM/SAX parser ,I can see several code on net for reading xml file using SAX/DOM parser but writing an xml file after reading it using ByteArrayInputStream I am not getting .A help through some example Link will also be helpful for me.
Thanks
Sumit
Edited by: user8687839 on Apr 30, 2012 2:37 AM
Edited by: user8687839 on Apr 30, 2012 2:43 AM

Thanks I got the result.
package com.sumit.collections;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteArrayInputStreamToXml {
     public static void main(String srg[]) throws IOException{
          InputStream inputStream= new FileInputStream("C:\\soft\\test2\\sample1.xml");
          ByteArrayOutputStream buffer = new ByteArrayOutputStream();
          int nRead; byte[] data = new byte[1024];
          while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
          buffer.write(data, 0, nRead); } buffer.flush();
          byte currentXMLBytes[]= buffer.toByteArray();
          /* byte currentXMLBytes[] = inputStream.toString().getBytes();*/
          ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
          OutputStream out = new FileOutputStream("C:\\soft\\test\\data.xml");
          int read=0;
          byte[] bytes = new byte[1024];
          while((read = byteArrayInputStream.read(bytes))!= -1){
          out.write(bytes, 0, read);
          out.write( '\n' );
          inputStream.close();
          out.flush();
          out.close();
          System.out.println("New file created!");
}

Similar Messages

  • Read from .txt file and output the content as two arrays

    I am using the contoured move to control the x-y stage. The trajectory datas for x and y axis are generated using my interpolation program and it is stored in a .txt file as two columns. What I want to do is read .txt file and output the content of this file as two arrays. Is there anyone has any ideas? Thanks, the .txt file is attached.
    Attachments:
    R.75.txt ‏172 KB

    Hi Awen,
    This is quite easy to do, you can merely use the "read from spreadsheet file" function to get a 2D array (2 columns and n rows) and then use the index array function to get whatever row/colums you want..
    Hope the attached VI helps you
    When my feet touch the ground each morning the devil thinks "bloody hell... He's up again!"
    Attachments:
    read sprdsheet file.vi ‏27 KB

  • How to create a file and store its contents into another file?

    Hi,
    I'm having some trouble trying to create a code where I have to to create a file and store its contents into another file?
    I read the API, but I'm not certain how this file thing works.
    Here's my code so far:
    public static void main(String[] args) throws Exception
              File file = new File("tasks.txt");
              if (file.exists())
                   System.out.println("File already exists");
                   System.exit(0);
              Scanner scan = new Scanner(System.in);
              Scanner scan2 = new Scanner(System.in);
              //Scans the input line by line
              scan.useDelimiter("\\n");
              //Scans the input by tabs
              scan2.useDelimiter("\\t");
              PrintWriter outputs = new PrintWriter("newtasks.txt");
              outputs.print("ok");
              outputs.println(3);
              outputs.close();
         }

    I managed to change my text into uppercase, but how do I store the uppercase content into another file.
    -So this is what I did so far, I took a text file and modified its strings to uppercase.
    -Now I need to put those modified strings into another text file, is there a way where I can do that with my current code?
    -I already tried printwriter, but it doesn't seem to work
    public static void main(String[] args)throws IOException
              //Task[] oneHundredTasks = new Task[100];
              String uppercase;
              String combine;
              Scanner scan = null;
              FileInputStream in = null;
            FileOutputStream out = null;
            PrintWriter output = null;
            try
                 scan = new Scanner(new BufferedReader(new FileReader("tasks.txt")));
                 scan.useDelimiter("\\n");
                 scan.useDelimiter("\\t");
                while (scan.hasNext())
                     if(!scan.hasNext())
                          scan.next();
                     combine = scan.next();
                     uppercase = combine.toUpperCase();
                     System.out.println(uppercase);
            finally
                if (scan != null)
                    scan.close();
            //The program will try the input and output files
            try
                 in = new FileInputStream("tasks.txt");
                out = new FileOutputStream("newtasks.txt");
                int c;
                //The number "-1" is used to indicate that it has reached the end of the stream.
                while ((c = in.read()) != -1)
                    out.write(c);
            finally
                if (in != null)
                    in.close();
                if (out != null)
                    out.close();
         }

  • Reading from a text file and displaying the contents with in a frame

    Hi All,
    I am trying to read some data from a text file and display it on a AWT Frame. The contents of the text file are as follows:
    pcode1,pname1,price1,sname1,
    pcode2,pname2,price2,sname1,
    I am writing a method to read the contents from a text file and store them into a string by using FileInputStream and InputStreamReader.
    Now I am dividing the string(which has the contents of the text file) into tokens using the StringTokenizer class. The method is as show below
    void ReadTextFile()
                        FileInputStream fis=new FileInputStream(new File("nieman.txt"));
                         InputStreamReader isr=new InputStreamReader(fis);
                         char[] buf=new char[1024];
                         isr.read(buf,0,1024);
                         fstr=new String(buf);
                         String Tokenizer st=new StringTokenizer(fstr,",");
                         while(st.hasMoreTokens())
                                          pcode1=st.nextToken();
                               pname1=st.nextToken();
              price1=st.nextToken();
                              sname1=st.nextToken();
         } //close of while loop
                    } //close of methodHere goes my problem: I am unable to display the values of pcode1,pname1,price1,sname1 when I am trying to access them from outside the ReadTextFile method as they are storing "null" values . I want to create a persistent string variable so that I can access the contents of the string variable from anywhere with in the java file. Please provide your comments for this problem as early as possible.
    Thanks in advance.

    If pcode1,pname1,price1,sname1 are global variables, which I assume they are, then simply put the word static in front of them. That way, any class in your file can access those values by simply using this notation:
    MyClassName.pcode1;
    MyClassName.pname1;
    MyClassName.price1;
    MyClassName.sname1

  • How to Compare 2 CSV file and store the result to 3rd csv file using PowerShell script?

    I want to do the below task using powershell script only.
    I have 2 csv files and I want to compare those two files and I want to store the comparision result to 3rd csv file. Please look at the follwingsnap:
    This image is csv file only. 
    Could you please any one help me.
    Thanks in advance.
    By
    A Path finder 
    JoSwa
    If a post answers your question, please click &quot;Mark As Answer&quot; on that post and &quot;Mark as Helpful&quot;
    Best Online Journal

    Not certain this is what you're after, but this :
    #import the contents of both csv files
    $dbexcel=import-csv c:\dbexcel.csv
    $liveexcel=import-csv C:\liveexcel.csv
    #prepare the output csv and create the headers
    $outputexcel="c:\outputexcel.csv"
    $outputline="Name,Connection Status,Version,DbExcel,LiveExcel"
    $outputline | out-file $outputexcel
    #Loop through each record based on the number of records (assuming equal number in both files)
    for ($i=0; $i -le $dbexcel.Length-1;$i++)
    # Assign the yes / null values to equal the word equivalent
    if ($dbexcel.isavail[$i] -eq "yes") {$dbavail="Available"} else {$dbavail="Unavailable"}
    if ($liveexcel.isavail[$i] -eq "yes") {$liveavail="Available"} else {$liveavail="Unavailable"}
    #create the live of csv content from the two input csv files
    $outputline=$dbexcel.name[$i] + "," + $liveexcel.'connection status'[$i] + "," + $dbexcel.version[$i] + "," + $dbavail + "," + $liveavail
    #output that line to the csv file
    $outputline | out-file $outputexcel -Append
    should do what you're looking for, or give you enough to edit it to your exact need.
    I've assumed that the dbexcel.csv and liveexcel.csv files live in the root of c:\ for this, that they include the header information, and that the outputexcel.csv file will be saved to the same place (including headers).

  • To upload the ZIP file and get the filenames available in ZIP file in ABAP

    Hi Experts,
    For my requirement, file from legacy comes as ZIP file with number of files in that.
    Please provide one code sample to upload the ZIP file from local workstation and get the filenames available in ZIP file to check few filename validation checks for the available files in report program.
    Thanks in Advance,
    Regards,
    Basani

    1. Copy the ZIP file into App server
    2. Call function
      call function 'RFC_REMOTE_PIPE'
        destination 'SERVER_EXEC'
        exporting
          command = command  " Unzip command gunzip /path & file
          read = 'X'
        tables
          pipedata = std_lines
    then you can read the files and can validate the file names

  • Reading a Blob (CSV file) and displaying the contents

    Hello Experts,
    I’m currently working on a system that allows the users to upload an Excel spreadsheet (.xls) in the system. The upload page is a PL/SQL cartridge. Then I’ve written a Java servlet (using Oracle Clean Content) to convert the XLS into a CSV and store it back in the database. (it is stored in the “uploaded_files” table as a blob). I’m trying to create another procedure to read the contents of the blob and display a preview of the data on the screen (using an html table (will be done using cartridge)). After the preview, the user can choose to submit the data into the database into the “detail_records” table or simply discard everything.
    Can anyone provide me any guidelines and/or code samples for reading the contents of a blob and displaying it as an html table? My data contains about 10 rows and 20 columns in the spreadsheet. I’ve been looking into using associative arrays or nested tables but I’m getting confused about how to implement them in my situation.
    Any help is greatly appreciated.

    BluShadow,
    Thanks for your response. The reason that it is a blob is that we use the same table for uploaded files for several applications. Some files are text, some excel, some other formats. Hence the table has been set up in a generic sense.
    However, in my procedure, I'm using
    DBMS_LOB.createtemporary and
    DBMS_LOB.converttoclob
    Is there any way you could possibly provide an example of how to read the contents of the file?

  • How to read a file and save the contents into array list

    i have textfile contains information like:
    Name: James Smith
    Customer no: 663,282
    Post code: BA1 74E
    Telephone no: 028-372632
    Last modified: Feb 10, 2008 6:50:00 PM GMT
    Name: Janet Smith
    Customer no: 663,283
    Post code: BA1 74E
    Telephone no: 028-372632
    Last modified: Jan 11, 2007 8:10:05 PM GMT
    etc...
    how can i read the contents of this textfile and put the data into an ArrayList called ArrayList<Customer> customerList.
    i knew that i need two classes, one for CustomerDetails and one for ReadFile.
    i have already done the customer class as:
    import java.util.Date;
    public class Customer
        String Name;
        int CustomerNo;
        String Postcode;
        String teleNo;
        Date lastModified;
        public Customer(String Name, int CustomerNo, String Postcode, String teleNo, Date lastModified)
         assign(Name, CustomerNo, Postcode, teleNo, lastModified);
        public void assign(String Name, int CustomerNo, String Postcode, String teleNo, Date lastModified)
         this.Name=Name;
         this.CustomerNo=CustomerNo;
         this.Postcode=Postcode;
         this.teleNo=teleNo;
         this.lastModified=lastModified;
        public String toString()
         String allDetails = "Name: "+Name+
             ", Customer No: "+CustomerNo+
             ", Postcode:"+Postcode+
             ", Telephone No: "+teleNo+
             ", Last Modified Date: "+lastModified;
         return allDetails;
    }i just wondering how can i code the ReadFile class?
    can anyone help me please. thank you in advance.

    thank you for your suggestion, but i have already started to code the readCustomer class using the Scanner.
    the code i got so far is:
    import java.util.Scanner;
    import java.io.*;
    public class readCustomer
        public static void main(String[] args)
         readCustomer("Customers.txt");
        public static void readCustomer(String filename)
         try {
             Scanner scanner = new Scanner(new File(filename));
             scanner.useDelimiter(System.getProperty("line.separator"));
             while (scanner.hasNext()) {
              processLine(scanner.next());
             scanner.close();
         } catch (FileNotFoundException e) {
             e.printStackTrace();
        public static void processLine(String line)
         Scanner scanner2 = new Scanner(line);
         scanner2.useDelimiter("\\s*:\\s*");
         String description = scanner2.next();
    *// here is where i am struggling. i don't know how to get the information after the : sign*   
    }i am currently struggling with the processLine method?
    also, i am not sure how to group a set of information and put them into the arraylist.
    Any hint, please. Thank you.
    Edited by: mujingyue on Feb 26, 2008 12:42 PM

  • Read the file and write the data into string or int

    Ok, here's another rookie question.
    I got to read the line from the file and store it in the memory as string or integer.
    I wrote this code:
    File inputFile = new File("c:/xxx.yyy");
    String outputString = new String();
    FileReader c1 = new FileReader(inputFile);
    StringWriter d1 = new StringWriter(outputString);
    int data;
             while((data = c1.read()) != -1)
                 d1.write(data);
                 System.out.println(data);
             c1.close();
             d1.close();This is how I see it, but it cannot be even compiled because there is no such thing as StringWriter(String) wich I find completely irrational. So tell me, am I retarded or what? No, but seriosly, please help the newbie to understand these streams, am I supposed to use some kind of buffer? Any help appreciated.

    A String is an immutable. You cannot update a String.
    A new String() is basically the same as an empty String ""
    An empty StringWriter can be created with new StringWriter().
    If you use a BufferedReader you can call readLine().
    BufferedReader in = new BufferedReader(new FileReader(filename));
    String line;
    while((line = in.readLine()) != null) {
      System.out.println(line);
    }

  • How to merge text files and put the result in a text file.

    Hi,
    I am trying to merge the files(text) using OWB and I would like to put the result in a file. Could any one please explain how to do this.
    Thanks and regards
    Gowtham Sen.

    using the unix commnad 'cat' along with the redirect '>>' will concat the files into one target
    #this will create the target file and over-write it if it existed already
    cat file1 > target
    ##Now add the rest of the files to the target, without over-writing
    cat file2 >>target
    cat file3 >>target
    cat file16 >> target
    You can then use an external table on the target file.
    A nicer way would be to user a 'for loop', but this will work fine.

  • Why do I get a NI-488 error massage when writing into a file and at the same time copiyng this file with a backup softwarre like Easy2Sync?

    I have a small LabVIEW program which writes random numbers very fast into a ASCII-file. I want that file to be copied to a new position every 10 min. Therefor I use a backup/synchronisation software which is doing a copy operation every 10 min. It works fine a certian amount of time and after a while I get either an LabVIEW error (LabVIEW: Fiel already open: NI-488 Comand requieres GPIB Controller to be System controller) or an backup-software error (couldn´t open file...whatever). I´m guessing, it has something to do with file-access but I don´t know why?!? If I run the LabVIEW program and I copy and paste the random-number-file with the windows explorer very fast (pressing ctrl+v rapidly) while LabVIEW is still writing into this file, no error appears. Can sombody help me?
    LabVIEW 2011

    Hi Serdj,
    you don't get a GPIB error, the error number has just 2 different explanations...
    Well, you have two programs accessing the same file. One program just wants to make a copy, the other (LabView) is trying to write to the file. When copying a file that is written to you get inconsistent results! That's why one of both programs is complaining an error...
    You can't have write and read access at the same time! (But you can have more than one read access at the same time...)
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • I created a new layer and copied the contents of another layer into the new layer. Now whenever I ed

    I have a template that I am editing. I have created new layers by duplicating an existing layer. The problem I am having is that anytime I make a change to a duplicated layer it changes the original as well. ie if I attempt to edit the action script on the new layer it changes the action script on the original? It seems as though they are linked and I can not find a way to unlink them??

    You should be able to edit the immediately present contents of different layers without affecting other layers, but if you are editing anything at a level below the layer, such as doubleclicking to edit an object in that timeline, you are changing it anywhere it is used.

  • Append the file and print the output in a single file in column manner

    Hi All,
    I have 2 files in UNIX.
    File1.txt
    NAME SAL
    Albert $4567
    Monali $7892
    Raj $8521
    File2.txt
    DOB
    12-JUL-1986
    5-Aug-1978
    13-MAR-1958
    so i apped both the file
    cat file1.txt file2.txt>>file3.txt
    The output of file3.txt was:
    NAME SAL
    Albert $4567
    Monali $7892
    Raj $8521
    DOB
    12-JUL-1986
    5-Aug-1978
    13-MAR-1958
    But i need the output below
    NAME SAL DOB
    Albert $4567 12-JUL-1986
    Monali $7892 5-Aug-1978
    Raj $8521 13-MAR-1958
    Could you please help me to resolve
    Edited by: user10069916 on Sep 6, 2012 12:07 AM

    $ man paste
    $ cat file1.txt
    NAME SAL
    Albert $4567
    Monali $7892
    Raj $8521
    $ cat file2.txt
    DOB
    12-JUL-1986
    5-Aug-1978
    13-MAR-1958
    $ paste file1.txt file2.txt >file3.txt
    $ cat file3.txt
    NAME SAL        DOB
    Albert $4567    12-JUL-1986
    Monali $7892    5-Aug-1978
    Raj $8521       13-MAR-1958
    $

  • How to read XML file and write into another XML file

    Hi all, I am new to JAVAXML.
    My problem is I have to read one XML file and take some Nodes from that and write these nodes into another XML file...
    I solved, how to read XML file
    But I don't know how to Write nodes into another XML.
    Can anyone help in this???
    Thanks in advance..

    This was answered a bit ago. There was a thread called "XML Mergine" that started on Sept 14th. It has a lot of information about what it takes to copy nodes from one XML Document object into another.
    Dave Patterson

  • Reading Data from Unix file and write into an Internal table

    Dear all,
                     I am having an requirement of reading data from unix file and write the same into an internal table..how to do that ...experts please help me in this regard.

    Hi,
    do like this
    PARAMETERS: p_unix LIKE rlgrap-filename OBLIGATORY.
    DATA: v_buffer(2047) TYPE c.
    DATA: BEGIN OF i_buffer OCCURS 0,
            line(2047) TYPE c,
    END OF i_buffer.
    * Open the unix file..
    OPEN DATASET p_unix FOR INPUT IN TEXT MODE.
    <b>IF sy-subrc NE 0.
    *** Error Message "Unable to open file.
    ELSE.</b>
       DO.
         CLEAR: v_buffer.
         READ DATASET p_unix INTO v_buffer.
         IF sy-subrc NE 0.
            EXIT.
         ENDIF.
         MOVE v_buffer TO i_buffer.
         APPEND i_buffer.
      ENDDO.
    ENDIF.
    CLOSE DATASET p_unix.
    <b>Reward points if it helps,</b>
    Satish

Maybe you are looking for

  • Conditional statement in html

    This is actually not a JSP question but an HTML question. I could'nt find any good html forum sites out there, and since I received excellent replies in my previous post, I am hoping that those of you who know JSP also know html. Heres my question, i

  • How can i relate my tables in order to get unique results

    Data given below is collected from three table ACCT_NO = 1242001063101 SYM_RUN_DATE     = 8/29/2012 ACTUAL_BALANCE = -7316.94 LEDGER_BALANCE_BASE = CLIENT_NO     = 1240000040 PROFIT_CENTRE = 206 BRANCH_NO = 124 CURRENCY     = PKR ACCT_TYPE = 101 DEPO

  • Microsoft Exchange 2013 eDiscovery - specific search query: looking for specific hyperlinks within e-mails content/body

    Dear all: I am currently using the MS Exchange 2013 eDiscovery feature with the objective to identify which of my users have received emails containing specific hyperlinks (e.g. http://website1/webroot/file.zip, http://website2/webroot/file.zip, etc.

  • Photo Stream is only seeing Scan #.jpg, not the Photo Title

    Can anyone tell me how to correct an issue I'm having between our iMac/iPhoto and Photo Stream... I scanned in about 500 photos of the family history and nammed each file with a descriptive text.  However, when I import the photos to the Photo Stream

  • Error in pipeline process

    Hi guys,   when is was posting a stock using MB1A using movement   type 201P. i get the following error.please do help me to come across these errors error : No stock posting possible for this material Regards Jino