Create file object from xml file in different package

I have my java class which is in a package...edu.xx.proj
It contains the following
File f = new File("formats.xml");
My xml file is in the package edu.xx.proj.xml
How do I get the file object for my xml file?
Ultimately I want that once the jar is shipped .. The path of xml file shld be independent of my OS path... it can only lookup the package path..
I will really appreciate it if someone can throw some input as to how to resolve this issue..
Thank you

I have my java class which is in a
package...edu.xx.proj
It contains the following
File f = new File("formats.xml");
My xml file is in the package edu.xx.proj.xml
How do I get the file object for my xml file?
Ultimately I want that once the jar is shipped .. The
path of xml file shld be independent of my OS path...
it can only lookup the package path..
I will really appreciate it if someone can throw some
input as to how to resolve this issue..
Thank you
InputStream inputStream = getClass().getResourceAsStream("xml/formats.xml");
/* OR */
URL url = getClass().getResource("xml/formats.xml");hth

Similar Messages

  • Dynamically create Value Objects from XML file

    Hi
    I want to create a value object from Xml file dynamically,like in the xml file i have the name of the variable and the datatype of the variable.is it possible do that,if so how.

    Read about apache's Digester tool. This is part of the Jakartha project. This tool helps in creating java objects from the XML files. I am not sure, if that is what u r looking for.

  • How to create Inbound Idoc from XML file-Need help urgently

    Hi,
    can any one tell how to create inbound Idoc from XML file.
    we have xml file in application server Ex. /usr/INT/SMS/PAYTEXT.xml'  we want to generate inbound idoc from this file.we are successfully able to generate outbound XML file from outbound Idoc by using the XML port. But not able to generate idoc from XML file by using we19 or we16.
    Please let me know the process to trigger inbound Idoc with out using  XI and any other components.
    Thanks in advance
    Dora Reddy

    Hi .. Did either of you get a result on this?
    My question is the same really .. I am testing with WE19 and it seems SAP cannot accept an XML inbound file as standard.
    I see lots of mention of using a Function Module.
    Am I correct in saying therefore that ABAP development is required to create a program to run the FM and process the idoc?
    Or is there something tht can be done with Standard SAP?
    Thanks
    Lee

  • Creating File objects from all files in a folder.

    Hi, I'm not too brilliant of a programmer, so this may be an obvious one that I could find in the API.
    My goal is to compare files for similarities and then give some output, that's not too important.
    My question is: How do I create an array of File objects from a folder of *.txt files, without creating each individually? Is there a way to simply get all the files from the folder?
    File I/O is still pretty new to me. If I didn't give a good enough explanation, please say so.
    Thank you very much!

    Note by the way that a File represents an abstract pathname, the idea of a file as a location. It doesn't specify the file's contents, nor does it require that the file it represents actually exists. A better name might be "theoretical file" or "directory listing entry".
    So getting a whole bunch of File objects is itself perhaps not necessary (although it could be useful).
    To expand on reply #1, look for File methods whose names start with "list".

  • Create an UDO from XML file

    Hello,
    I would want to create an UDO from an XML file. But I don't see any documentation about it.
    Do you know if there is any sample or something?
    Thanks in advance

    Hi Martin,
    I don't know if this is possible as I looked at the properties of the UDO object (SAPbobsCOM.UserObjectsMD) and there are no XML methods. As with the other meta data objects, like UserTablesMD and UserFieldsMD you have SaveXML and GetAsXML, but not with UDO.
    Hope it helps,
    Adele

  • Create web pages from xml files using Servets or JSP

    I�m new in this tecnology and I have to create a web pages from information that I get from a XML files. I would like to know if there is a place where I can find examples of code or any book that could help me.

    Two places with loads of information on this:
    http://xml.apache.org
    Look at Xalan or Cocoon.
    Also, there was an article on http://www.javaworld.com on XML with JSP.

  • How to generate Java objects from XML files with out  scema compilation

    Dear participants,
    My name is Raghavendra , i have a requirement of reading XML files Dynamically and parse them and create java types for manipulation . i will not be provided with sxd files (no schema compilation )coz no one knows how many types of structures are there. i want a generic solution. Please Help.
    Thanks ,
    Raghavendra Ach
    you can mail me to " [email protected]"

    georgemc wrote:
    You could also look at something like Apache Digester, which will parse your XML and populate Java objects with the data. A slightly steeper learning curve than the lower-level APIs such as JDOM, but that's outweighed by the lesser development effortdon't think that would work for the original problem, which seemed to indicate that the xml had an unknown structure.

  • How to creat COM object from dll file?

    Hi,
    I tried to read about this topyc, but I didn't found eny example that creat
    COM object. I downloaded jacob.jar
    then I writed:
    ActiveXComponent ax = new ActiveXComponent("C:/MyJava/deploy/SMSCom.dll");
    Object SMSObj = ax.getObject();
    I get error (I put jacob.jar with all athers jars, I don't know way this erre)
    Exception occurred during event dispatching:
    java.lang.UnsatisfiedLinkError: no jacob in java.library.path
         at java.lang.ClassLoader.loadLibrary(Unknown Source)
         at java.lang.Runtime.loadLibrary0(Unknown Source)
         at java.lang.System.loadLibrary(Unknown Source)
         at com.jacob.com.Dispatch.<clinit>(Dispatch.java)file name: SMSCom.dll
    object name: SMSSender
    In VB this is the code:
    Object SMSObj = CreateObject("SMSCom.SMSSender");
    SMSObj.password = pass;
    SMSObj.Username = name;
    SMSObj.Source = phone;Thanks

    In Eclipse:
    1- To include jacob.jar for compile / run:
    Choose the Java perspective, then in the Package Explorer right-click on the project and choose Properties.
    Select Java Build Path from the left pane then the Librairies pane from the right.
    Click on Add External Jars button and select the jacob.jar file then click Open then Ok.
    2- To make jacob.dll and SMSCom.dll "visible" for run:
    Open your Debug (or Run) Java application configuration (the one for your project's main class).
    Select the Environment pane then click on Select button.
    Select Path and click on Ok button.
    Then re-select Path and click on Edit button.
    Add the two appropriate folders for jacob.dll and SMSCom.dll in the Path and click on Ok then Apply.
    Regards

  • Create a File object from a file in a .jar

    i looked for 2 hours...
    i tired this:
    URL url =  MyClass.class.getResource("filename.dat");
    File file = new File(url.getFile());i give up.

    The problem is that the file inside a Jar file is not
    a file. The jar file just contains a stream of bytes
    in the format needed to make the Jar file. Jar files
    are not folders like in the directory. So to get at
    the contents of the Jar file you need to read the Jar.
    The getResource method returns the URL which is a
    file URL, but this only works because Java has
    handlers that deal with getting the contents from a
    Jar file based on this type of URL. A URL cannot
    just be made into a file. I'm not sure that the File
    object can handle this type of file URL (I guess not
    or we wouldn't be having this discussion). So really
    it just depends what you want do. If you want to
    extract the file, just read the data in from the
    inputstream gotten from the URL, or better just call
    getResourceAsStream(), and read the bytes into an
    array. After this, you can do whatever, write it as
    a file to the hard drive, convert to a string, get
    the size based on the array length. makes sense, but how could i get an InputStream into an array, dont i need the size of the array first? and i dont think i can use InputStream.available()to figure it out... i tired downcasting to a FileInputStream yet no avail.

  • Create java objects from xml

    I want to create a tree structure for java object. These java objects are populated after the parsing the xml. But what could be the logic for adding child to parent when there are
    many sub nodes? I wanted to use one recursive function which iterate through all the elements of the xml file. But I have not got the idea how to add one child object to parent object.
    following are my classes. Any help on this highly appreciated.
    public class TreeObject {
              private String name;
              private TreeParent parent;
              public TreeObject(String name) {
                   this.name = name;
              public String getName() {
                   return name;
              public void setParent(TreeParent parent) {
                   this.parent = parent;
              public TreeParent getParent() {
                   return parent;
              public String toString() {
                   return getName();
    import java.util.ArrayList;
    public class TreeParent extends TreeObject {
         private TreeObject treeObject ;
              private ArrayList children;
              public TreeParent(String name) {
                   super(name);
                   children = new ArrayList();
              public void addChild(TreeObject child) {
                   children.add(child);
                   child.setParent(this);
                   treeObject = child ;
              public void removeChild(TreeObject child) {
                   children.remove(child);
                   child.setParent(null);
              public TreeObject [] getChildren() {
                   return (TreeObject [])children.toArray(new TreeObject[children.size()]);
              public boolean hasChildren() {
                   return children.size()>0;
              public TreeObject getChild(){
                   return treeObject;
    private TreeParent getChilderen(Element rootNode){
         List list = rootNode.getChildren();
         String rootNodeName = rootNode.getName();
         TreeParent root = new TreeParent(rootNodeName);
         for (int i=0; i< list.size(); i++)
    Element node = (Element) list.get(i);
    if(node.getChildren().size() > 0){
         // TreeParent treeParent = new TreeParent(node.getText());
         TreeParent treesub = new TreeParent(node.getText());
         treesub.addChild(treesub);
         //TreeParent p = treeParent.getParent();
         // rootParent.addChild(treeParent);
    }else{
         TreeObject object = new TreeObject(node.getText());
         root.addChild(object);
    getChilderen(node);
         return root ;
    public TreeParent buildTree(String filePath) {
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File(filePath);
    try{
    Document document = (Document) builder.build(xmlFile);
    Element rootNode = document.getRootElement();
    // List list = rootNode.getChildren("staff");
    TreeParent rootParent = getChilderen(rootNode);
    return rootParent ;
    }catch(IOException io){
    System.out.println(io.getMessage());
    }catch(JDOMException jdomex){
    System.out.println(jdomex.getMessage());
    return null;
    Edited by: 870611 on Jul 6, 2011 6:27 AM

    Hi
    I recommend you use the API JAXB. Is much simpler.
    here a link: http://www.oracle.com/technetwork/articles/javase/index-140168.html
    here a example: http://download.oracle.com/javaee/5/tutorial/doc/bnbay.html#bnbbc

  • Create value object from xml

    So I've got a value object with 100 fields.
    I have a ASP.net web service that returns the value objects
    as XML (I really don't want to use WebOrb...).
    I don't want to write a lot of code like this:
    vo.Field1 = voXML.Field1;
    vo.Field2 = voXML.Field2;
    vo.Field3 = voXML.Field3;
    Is there an easier/faster way to do this? Can't I do some
    sort of for/each loop. The element names are identical to the field
    names.
    Thanks.

    http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Live Docs_Book_Parts&file=usingas_053_9.html#220936

  • Create dynamic column from xml file

    Hi All,
           <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"  layout="absolute" backgroundColor="white" width="500" height="300" creationComplete="onload()" >
    <mx:Style>
        DataGrid {
            alternatingItemColors: #a1a1a1,#8bb8e6;       
            borderColor:#050505; borderStyle:outset;        
            color:#ffffff;       
            editable:false;         
               fontSize:11; fontWeight:bold; fontFamily:Tahoma;          
               horizontalGridLines:false;
               headerStyleName:myHeaderStyles;
                    headerSeparatorSkin:ClassReference("mx.skins.ProgrammaticSkin");    
        rollOverColor:#5CC2F7;    
        selectionColor:#E8C76D; sortableColumns:true;   
        textAlign:center; textRollOverColor:#FD0606; textSelectedColor:#1301FF;   
        variableRowHeight:true;
        verticalAlign:middle; verticalGridLines:false; verticalGridLineColor:#050505;   
    wordWrap: false; 
    .myHeaderStyles
                color: #ffffff;
                fontWeight: bold; fontFamily:Arial; fontSize:13;
    </mx:Style>
    <mx:Script>
    <![CDATA[
    import mx.collections.ArrayCollection;
       import mx.charts.renderers.CircleItemRenderer;
       import mx.charts.series.ColumnSeries;
       [Bindable]
        public var myData:ArrayCollection;
    private var now:Date=new Date();
    private var str:String;
    private var st:String;
    public function onload():void
    str=String(now.getDate())+' '+String(now.getMonth())+' '+String(now.getFullYear())+' '+String(now.getHours())+' '+String(now.getMinutes()+' '+String(now.getSeconds()));
    trace(str);
    st=srv.url="Data/NumberChart.xml?rand="+str;
    trace(st);
    srv.send();
    public function onresult():void
    myData=ArrayCollection(srv.lastResult.Document.Record)
    trace(myData);
    ]]>
    </mx:Script>
    <!-- xml path (data passing) -->
      <mx:HTTPService id="srv"         result="onresult()"  /> 
      <mx:WipeRight id="myWR" duration="2000"/>
        <mx:WipeLeft id="myWL" duration="2000"/>   
        <mx:HBox label="Home Team" width="100%" height="100%" backgroundColor="white">
    <mx:DataGrid id="HomeTeam" dataProvider="{myData}" creationCompleteEffect ="{myWR}"   width="500" height="300"  headerBackgroundSkin="@Embed(source='assets/Tileimage4movieplayer_img.png')">
    <mx:columns>
    <mx:DataGridColumn id="Hcol1" headerText="Player" draggable="false" dataField="DisField" width="170" showDataTips="true" wordWrap="true"  />
    <mx:DataGridColumn id="Hcol2" headerText="Average" draggable="false" dataField="Value" width="170" showDataTips="true" wordWrap="true"  />
    <mx:DataGridColumn id="Hcol3" headerText="Matchs" draggable="false" dataField="Prefix" width="170" showDataTips="true" wordWrap="true"  />
    </mx:columns>
    </mx:DataGrid>
    </mx:HBox>
    </mx:Application>
    and my xml code is...
    <?xml version='1.0' encoding='utf-8' ?>
    <Document Title='50 Runs Milestone'>
    <Record>
    <DisField>K Sangakkara</DisField>
    <Value>200.00</Value>
    <runs>50</runs>
    <Prefix>KXIP Vs DC</Prefix>
    </Record>
    <Record>
    <DisField>R Sharma</DisField>
    <Value>185.19</Value>
    <Prefix>KXIP Vs DC</Prefix>
    <runs>50</runs>
    </Record>
    <Record>
    <DisField>W Jaffer</DisField>
    <Value>151.52</Value>
    <Prefix>BRC Vs CSK</Prefix>
    <runs>50</runs>
    </Record>
    <Record>
    <DisField>G Gambhir</DisField>
    <Value>135.14</Value>
    <Prefix>CSK Vs DD</Prefix>
    <runs>50</runs>
    </Record>
    <Record>
    <DisField>M Boucher</DisField>
    <Value>125.00</Value>
    <Prefix>KKR Vs BRC</Prefix>
    <runs>50</runs>
    </Record>
    <Record>
    <DisField>A Gilchrist</DisField>
    <Value>119.05</Value>
    <Prefix>KXIP Vs DC</Prefix>
    <runs>50</runs>
    </Record>
    <Record>
    <DisField>S Asnodkar</DisField>
    <Value>113.64</Value>
    <Prefix>RR Vs BRC</Prefix>
    <runs>50</runs>
    </Record>
    </Document>
    it's working but i want to crete dynamic datagrid column how to do it any idea?

    I actually found this topic interesting, so I made the data and code generic and created a Flex Cookbook entry, adding the ability to remove columns as well:
    <?xml version='1.0' encoding='utf-8' ?>
    <Document>
      <Record>
        <name>Bob Smith</name>
        <age>48</age>
        <sales>$53,000.00</sales>
        <territory>Southeast</territory>
      </Record>
      <Record>
        <name>Susan Sharma</name>
        <age>37</age>
        <sales>$37,000.00</sales>
        <territory>Southwest</territory>
      </Record>
      <Record>
        <name>George Freebird</name>
        <age>52</age>
        <sales>$49,000.00</sales>
        <territory>Midwest</territory>
      </Record>
    </Document>
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
      creationComplete="srv.send();" >
      <mx:Script>
        <![CDATA[
          import mx.controls.Alert;
          import mx.collections.ArrayCollection;
          [Bindable] public var myData:ArrayCollection;
          public function onresult():void{
            myData=ArrayCollection(srv.lastResult.Document.Record)
          private function modifyColumns(evt:MouseEvent):void{
            var ac:ArrayCollection = new ArrayCollection(SalesData.columns);
            var actionTaken:Boolean = false;
            if(evt.currentTarget.label=="Remove Column"){
              for each(var col1:DataGridColumn in ac){
                if(col1.headerText == headerTxt.text){
                  ac.removeItemAt(ac.getItemIndex(col1));
                  headerTxt.text = "";
                  SalesData.columns = ac.toArray();
                  actionTaken = true;
              if(actionTaken){
                mx.controls.Alert.show("Column " + headerTxt.text + " was removed.");
              }else{
                mx.controls.Alert.show("Column " + headerTxt.text + " not found.");
            }else if(evt.currentTarget.label=="Add Column"){
              for each(var col:DataGridColumn in ac){
                if(col.headerText == headerTxt.text){
                  mx.controls.Alert.show("Column " + headerTxt.text + " already exists.");
                  return;
              var dgc:DataGridColumn = new DataGridColumn();
              dgc.headerText = headerTxt.text;
              dgc.dataField = datafieldTxt.text;
              dgc.width = 100;
              ac.addItemAt(dgc, int(columnIndexTxt.text));
              SalesData.columns = ac.toArray();
              headerTxt.text = "";
              datafieldTxt.text = "";
              columnIndexTxt.text = "";
              mx.controls.Alert.show("Column " + headerTxt.text + " was added.");
        ]]>
      </mx:Script>
      <mx:HTTPService id="srv" url="data.xml" result="onresult()"/> 
      <mx:DataGrid id="SalesData" dataProvider="{myData}" width="500" height="300">
        <mx:columns>
          <mx:DataGridColumn headerText="Name" dataField="name" width="170"/>
          <mx:DataGridColumn headerText="Sales" dataField="sales" width="170"/>
          <mx:DataGridColumn headerText="Territory" dataField="territory" width="170"/>
        </mx:columns>
      </mx:DataGrid>
      <mx:Form label="Add or Remove a Column">
        <mx:FormItem label="Enter column header text:">
          <mx:TextInput id="headerTxt"/>
        </mx:FormItem>
        <mx:FormItem label="Enter column datafield (if adding):">
          <mx:TextInput id="datafieldTxt"/>
        </mx:FormItem>
        <mx:FormItem label="Enter zero based new column index (if adding):">
          <mx:TextInput id="columnIndexTxt"/>
        </mx:FormItem>
        <mx:FormItem label="Click to add or remove column">
          <mx:HBox>
            <mx:Button label="Add Column" click="modifyColumns(event);"
              disabledColor="0xf1aa99"
              enabled="{headerTxt.text!=''&amp;&amp;datafieldTxt.text!=''&amp;&amp;columnIndexTxt.text! =''}"/>
            <mx:Button label="Remove Column" click="modifyColumns(event);"
              disabledColor="0xf1aa99" enabled="{headerTxt.text!=''}"/>
          </mx:HBox>
        </mx:FormItem>
      </mx:Form>
    </mx:Application>

  • How to create value objects from xml

    I am receiving xml back from my web service ( e4x ). I am
    trying to figure out how to create a value object without having to
    manually fetch each value in the value objects constructor. I am
    using introspecton in my Java web service to do this. Is there such
    a thing in Action Script?
    Anyone done this before that can share some code???? Any help
    would be very much appreciated.

    That's twice now I've heard that. lol.
    I am using Cairngorm and I suppose out of ignorance perhaps,
    I am using VO's. So my web service would return an Object Proxy and
    I have some code that could create objects dynamically from the
    results. The objects had to be simple of course and now they are
    becoming more complex thus the need to change to e4x instead of
    objects.
    So now I am trying to convert the xml result into the desired
    VO to be used throughout the rest of the application. I'm not sure
    how to use Cairngorm without the VO's they are tied to everything.
    Are you familiar with the architecture? Your thoughts?

  • Create File Object from a remote file

    Hi,
    I would like to know about how to create a new File object from a file in a remote machine, it is a web application, i have the remote route of the file, and if I need the ip of the remote machine, I would like to know how to get it too.
    File fileobject = new File(�What do I have to put here or before or whatever?);
    Thank you very much.
    J.

    First, from the technical point of view you can't create a File object unless it's a file on the computer where the code is running. It doesn't matter if you have an IP address or something, if you haven't mapped a drive to it you can't create a File object.
    But more importantly, you can't just reach out from your server and grab a file from the client's computer. That's an obvious security violation and if you didn't realize that you shouldn't be designing web applications yet. If you want a file uploaded then you have to provide the client with an HTML form where they select a file to be uploaded.

  • How to automatically create fillable PDFs from XML

    We are looking for a way to create fillable PDFs that users can enter data into and save (so the PDF needs Reader Rights applied) and we want to be able to automatically create these PDFs from XML files. We are able to do what we want in a manual fashion using Acrobat Pro v8 but we need a way to automate this due to the volume of XML files that we will need to convert.
    Is there any way that this can be scripted from a command line interface with Acrobat.. like:
    Acrobat.exe –input FileName.xml –output FileName.pdf –applyReaderRights true
    If there is no command line options for this is there any way that this could be coded using .NET or any other programming language?

    You cannot automate applying usage rights with Acrobat. For that you'd need to use Adobe's LiveCycle Reader Extensions.
    How exactly are you currently converting XML into fillable forms? Are you using an XDP to somehow convert to an XFA-based PDF?

Maybe you are looking for

  • Performance of top-n analysis queries

    Hi, I am trying to understand how top-n queries work w.r.t performance. I have 10 lakh records in my table out of my query filters. I just want to retrieve top 1000 records. i.e. select * from t where x=y; -- returns 10,00,00,000 records To retrieve

  • Inserting data into custom infotype

    Hi, I`m trying to enter an employee record into a custom infotype (which basically belongs to PA ).   I`m using the FM 'HR_INFOTYPE_OPERATION' and usage of FM is as below. But the infotype is not getting updated with the values. IF NOT I_9111 IS INIT

  • Skype button code not working

    This week I had an email from skype saying that the old api code for showing status and calling was going to be retired on 15th May so i followed the instructions and the new cose wont work I chat messaged the support team, and they were unhelpful -

  • Simple servlet doing a Get method.

    I've tried to use the below code to call a URL using get function. Although it seems to produce a POST. Waht is wrong? I'm looking for a way to simulate an URL get call. Please help. url = new URL("http://mycomputer/cgi-bin/ccmInterface?cmd=verify&se

  • How to add include in MV45AFZZ ??

    Hi, In ECC 6.0, I need to add code in the user exit FORM USEREXIT_SAVE_DOCUMENT ENDFORM. How do I do that ? Should I have to implement the implicit enhancement point present at this spot in the include MV45AFZZ ? Or any other way ? I just need to add