Urgent help for processing XML stream read from a JAR file

Hi, everyone,
     Urgently need your help!
     I am reading an XML config file from a jar file. It can print out the result well when I use the following code:
===============================================
InputStream is = getClass().getResourceAsStream("conf/config.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line); // It works fine here, which means that the inputstream is correct
// process the XML stream I read from above
NodeIterator ni = processXPath("//grid/gridinfo", is);
Below is the processXPath() function I have written:
public static NodeIterator processXPath(String xpath, InputStream byteStream) throws Exception {
// Set up a DOM tree to query.
InputSource in = new InputSource(byteStream);
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(true);
Document doc = dfactory.newDocumentBuilder().parse(in);
// Use the simple XPath API to select a nodeIterator.
System.out.println("Querying DOM using " + xpath);
NodeIterator ni = XPathAPI.selectNodeIterator(doc, xpath);
return ni;
It gives me so much errors:
org.xml.sax.SAXParseException: The root element is required in a well-formed doc
ument.
at org.apache.xerces.framework.XMLParser.reportError(XMLParser.java:1213
at org.apache.xerces.framework.XMLDocumentScanner.reportFatalXMLError(XM
LDocumentScanner.java:570)
at org.apache.xerces.framework.XMLDocumentScanner$XMLDeclDispatcher.endO
fInput(XMLDocumentScanner.java:790)
at org.apache.xerces.framework.XMLDocumentScanner.endOfInput(XMLDocument
Scanner.java:418)
at org.apache.xerces.validators.common.XMLValidator.sendEndOfInputNotifi
cations(XMLValidator.java:712)
at org.apache.xerces.readers.DefaultEntityHandler.changeReaders(DefaultE
ntityHandler.java:1031)
at org.apache.xerces.readers.XMLEntityReader.changeReaders(XMLEntityRead
er.java:168)
at org.apache.xerces.readers.UTF8Reader.changeReaders(UTF8Reader.java:18
2)
at org.apache.xerces.readers.UTF8Reader.lookingAtChar(UTF8Reader.java:19
7)
at org.apache.xerces.framework.XMLDocumentScanner$XMLDeclDispatcher.disp
atch(XMLDocumentScanner.java:686)
at org.apache.xerces.framework.XMLDocumentScanner.parseSome(XMLDocumentS
canner.java:381)
at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1098)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.
java:195)
at processXPath(Unknown Source)
Thank you very much!
Sincerely Yours
David

org.xml.sax.SAXParseException: The root element is required in a well-formed document.This often means that the parser can't find the document. You think it should be able to find the document because your test code could. However if your test code was not in the same package as your real (failing) code, your test is no good because getResourceAsStream("conf/config.xml") is looking for that file name relative to the package of the class that contains that line of code.
If your test code wasn't in any package, put a slash before the filename and see if that works.

Similar Messages

  • Read from own jar file

    Using netBeans IDE 4.1 I wrote a stand-lone application contained in a single jar file. It transforms xml files into drawings. I'd like to distribute the application with some sample xml-files in that one jar-file. But how can I make the application read these embedded files?
    I looked at the SplitPaneDemo that uses a list of images to display.
    http://java.sun.com/docs/books/tutorialJWS/uiswing/components/example-1dot4/SplitPaneDemo.jnlp
    works.
    I also downloaded
    http://java.sun.com/docs/books/tutorialNB/download/tut-examples.zip
    extracted uiswing/components/example-swing
    created a new project from existing sources
    made SplitPaneDemo the main class
    and run it after a clean build.
    The images are in the jar-file, but no images appear.
    Is the problem in the second attempt a missing classpath? In that case: how can I prevent my a-technical users having to set a classpath, or how can I find out and use the absulute path to the jar-file?
    Jo

    But my browser (FireFox 1.0.7 on Windows XP Home edition) isn't launched (and no error shown) with
    String url = "" +getClass().getClassLoader().getResource("path/to/page.html");
    try {
                Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + url);
    } catch (java.io.IOException e) {
                javax.swing.JOptionPane.showMessageDialog
                        ( this
                        , url
                        , "debug info"
                        , javax.swing.JOptionPane.INFORMATION_MESSAGE
    }

  • Creating a JAR File for a program that depends on other JAR files

    Hi, I'm pretty new to this so it shouldn't be terribly hard to answer:
    I have a program which uses JGoodies. There are 2 JGoodies .jar files in the same directory as my program. So I compile it by doing:
    javac -extdirs . NameOfMyProgram.java
    First off, is this the best way to do it? Is there any way of 'calling' these JAR files from within NameOfMyProgram.java?
    Secondly, if I then try to run it by doing java NameOfMyProgram, it doesn't work; can't find the JGoodies stuff. I end up having to add the classpaths of the unzipped JGoodies directories.
    So I have 2 questions:
    1. How can I execute my file so that it reads from the JAR files, not the big expanded folders that I unzipped?
    2. How can I create a JAR file that reads the JGoodies files properly? Right now, I have a Manifest.txt file that looks like:
    Main-Class: NameOfMyProgram
    Class-Path: forms-1.0.5.jar
    Class-Path: looks-1.3.1.jar
    Thanks a lot for your help!

    - learn how to use mysql JDBC
    - pack JDBC driver only
    - remotely access your DB
    - set proper security level for your app

  • Help! Want to read from a xl file and get an output voltage value!!!

    Hello..
    I`m a beginner, so please help..
    My program should output an voltage value that is read from an xl-file with one collum. The most important is that each values in the xl graph should be read per iteration. So that the file is read over time. I want to use this xl file to controll the output signal over time.
    Can anyone show me how this VI would look like, and what would the xl file look like??

    The easiest way to do this is to save your Excel file as a comma or tab separated text file and not the native Excel format. Then you can use Read From Spreadsheet File (on the File I/O palette). Using this, you can read the file all at once and then just have a 1D array that you can wire to a while or for loop so that with each iteration of the loop, you get one element in the array. A for loop automatically indexes an input array. Reading the file all at once will be more effecient that reading the file line by line.

  • Reading an xml file from a jar file

    Short question:
    Is it possible to read an xml file from a jar file when the dtd is
    placed inside the jar file? I am using jdom (SAXBuilder) and the default
    sax parser which comes with it.
    Long Question:
    I am trying to create an enterprise archive file on Weblogic 6.1. We
    have a framework that is similar to the struts framework which uses it's
    own configuration files
    I could place the dtd files outside the jar ear file and specify the
    absolute path in an environment variable in web.xml which is
    configurable through the admin console.
    But I want to avoid this step and specify a relative path within the jar
    file.
    I have tried to use a class which implements the entityresolver as well
    as try to extend the saxparser and set the entity resolver within this
    class explicitly, but I always seem to sun into problems like:
    The setEntityresolver method does not get called or there is a
    classloader problem. i.e. JDOM complains that it cannot load My custom
    parser which is part of the application
    Vijay

    Please contact the main BEA Support team [email protected]
    They will need to check with product support to determine
    the interoperatablity of Weblogic Server with these other
    products.

  • Getting repeated values when reading from a text file.

    I need to read from a text file. When the token encounters a particular word (command) I need to read the next line and perform some actions. However, this part is working but it is repeating the values again and again until it encounters the next particular word (command). Hope that someone will help me out, as always when I posted a problem in these forums.
    SetOperations class - contains the set methods
    // Imported packages.========================================================
    import java.util.Vector;
    import java.util.Iterator;
    // Public class SetOperations.===============================================
    public class SetOperations
         // Instance variables.===================================================
         private Vector v = null; // Creates new instance of vector.
         protected int memberCount;
         // Constructor.==========================================================
         public SetOperations()
              v = new Vector();
         } // end constructor.
         // Method isMember.======================================================
         * Checks whether the element is already a member of the set.
         * @return True if Vector v contains Object member.
         public boolean isMember(Object member)
              if (member != null) // only if Object member is not null.
                   return v.contains(member); // returns true if vector already contains member.
              else
                   return false; // returns false if vector does not contain member.
         } // end public boolean isMember(Object member).
         // Method addMember.=====================================================
         * Adds a member to the set.
         * @return Adds Object member to Vector v.
         public void addMember(Object member)
              //if (! v.contains(member)) // only if element is not already a member.
              if (isMember(member) == false) // only if element is not already a member.
                   v.add(member); // adds a member.
         } // end public void addMember(Object member).
         // Method countMember.===================================================
         * Returns the number of members present in the vector.
         * @return Number of elements present in the vector.
         public int countMember()
              return v.size();
         } // end public int countMember().
         // Method isSetEmpty.====================================================
         * Returns true if set is empty.
         * @return True if no elements are present in Vector v.
         public boolean isSetEmpty()
              return v.size() == 0; // returns 0 if no elements are present in the vector.
         } // end of public boolean isSetEmpty().
         // Method printMember.===================================================
         * Displays member/s of the set.
         * @return Prints element/s present in the vector.
         public void printMember()
              for (int i = 0; i < v.size(); i++) // iterates through present members.
                   System.out.println("[" + i + "] " + v.get(i)); // displays member/s present in the vector.
         } // end of public void printMember().
    } // end public class SetOperations.
    SetTextLauncher class - reads from a text file and implements the set operations
    // Imported packages.========================================================
    import java.util.*;
    import java.io.*;
    // Public class SetTestLauncher.=============================================
    public class SetTestLauncher
         // Main method public static void main(String args[]).===================
         public static void main(String args[])
              displayFile("test.txt"); // outputs result from text file.
         // method to display a file on screen
         public static void displayFile (String textFile)
              // Instance variables.===============================================
              // Creates new instances of SetOperations.
              SetOperations setA = new SetOperations();
              SetOperations setB = new SetOperations();
              SetOperations setC = new SetOperations();
              SetOperations setD = new SetOperations();
              SetOperations setE = new SetOperations();
              // Initialisation.
              String line = "", nextLine = "";
              FileReader fr = null;
              try
                   // Opens the file with the FileReader data sink stream.
                   fr = new FileReader(textFile);
                   // Converts the FileReader input stream with the BufferedReader processing stream.
                   BufferedReader br = new BufferedReader(fr);
                   // Iterates through text file reading lines until end of text lines.
                   while (line != null)
                        line = br.readLine(); // reads one line at a time.
                        if(line == null) break; // when the line is null break the loop.
                        // Creates a new instace of StringTokenizer.
                        StringTokenizer st = new StringTokenizer(line);
                        // Loops until there are no more tokens.
                        while (st.hasMoreTokens())
                             String token = st.nextToken(); // reads next token.
                             // Only if the token encounters the String "membera".
                             if(token.equals("membera"))
                                  nextLine = br.readLine(); // gets next line.
                                  setA.addMember(nextLine); // adds a member to the set.
                                  // Displays members present in the set if vector is not empty.
                                  if (! setA.isSetEmpty())
                                       setA.printMember(); // print members present.
                                  // Displays the number of member/s present in the vector.
                                  System.out.println("Number of set members: " + setA.countMember());
              // Catches and displays exceptions.
              catch (FileNotFoundException exp)
                   System.out.println(exp.getMessage());
                   exp.printStackTrace();
              catch (IOException exp)
                   System.out.println(exp.getMessage());
                   exp.printStackTrace();
              finally
                   try
                        // if file is found
                        if (fr != null)
                             // close file
                             fr.close();
                   catch (IOException exp)
                        exp.printStackTrace();
         } // end public static void main(String args[]).
    } // end public class SetTestLauncher.

    Thanks for your interest. Please ignore SetOperations class, it is just the class containing the methods and it works correctly since I checked it without reading from a text file. I marked the part where I think lies my problem in class SetTestOperations.
    The information in the text file is as follows:
    membera
    Hillman
    membera
    Skoda
    membera
    Honda
    membera
    Toyota
    and the result is:
    [0] Hillman
    Number of set members: 1
    [0] Hillman
    [1] Skoda
    Number of set members: 2
    [0] Hillman
    [1] Skoda
    [2] Honda
    Number of set members: 3
    [0] Hillman
    [1] Skoda
    [2] Honda
    [3] Toyota
    Number of set members: 4
    instead of just one set:
    [0] Hillman
    [1] Skoda
    [2] Honda
    [3] Toyota
    Number of set members: 4
    Hope it is easier to understand like this.
    Regards
    Marco
    I need to read from a text file. When the token
    encounters a particular word (command) I need to read
    the next line and perform some actions. However, this
    part is working but it is repeating the values again
    and again until it encounters the next particular
    word (command). Hope that someone will help me out,
    as always when I posted a problem in these forums.
    SetOperations class - contains the set
    methods
    // Imported
    packages.=============================================
    ===========
    import java.util.Vector;
    import java.util.Iterator;
    // Public class
    SetOperations.========================================
    =======
    public class SetOperations
    // Instance
    e
    variables.============================================
    =======
    private Vector v = null; // Creates new instance of
    f vector.
         protected int memberCount;
    Constructor.==========================================
    ================
         public SetOperations()
              v = new Vector();
         } // end constructor.
    // Method
    d
    isMember.=============================================
    =========
    * Checks whether the element is already a member of
    f the set.
         * @return True if Vector v contains Object member.
         public boolean isMember(Object member)
    if (member != null) // only if Object member is not
    ot null.
    return v.contains(member); // returns true if
    if vector already contains member.
              else
    return false; // returns false if vector does not
    not contain member.
         } // end public boolean isMember(Object member).
    // Method
    d
    addMember.============================================
    =========
         * Adds a member to the set.
         * @return Adds Object member to Vector v.
         public void addMember(Object member)
    //if (! v.contains(member)) // only if element is
    is not already a member.
    if (isMember(member) == false) // only if element
    nt is not already a member.
                   v.add(member); // adds a member.
         } // end public void addMember(Object member).
    // Method
    d
    countMember.==========================================
    =========
    * Returns the number of members present in the
    e vector.
         * @return Number of elements present in the vector.
         public int countMember()
              return v.size();
         } // end public int countMember().
    // Method
    d
    isSetEmpty.===========================================
    =========
         * Returns true if set is empty.
    * @return True if no elements are present in Vector
    r v.
         public boolean isSetEmpty()
    return v.size() == 0; // returns 0 if no elements
    ts are present in the vector.
         } // end of public boolean isSetEmpty().
    // Method
    d
    printMember.==========================================
    =========
         * Displays member/s of the set.
         * @return Prints element/s present in the vector.
         public void printMember()
    for (int i = 0; i < v.size(); i++) // iterates
    es through present members.
    System.out.println("[" + i + "] " + v.get(i)); //
    // displays member/s present in the vector.
         } // end of public void printMember().
    } // end public class SetOperations.
    SetTextLauncher class - reads from a text file
    and implements the set operations
    // Imported
    packages.=============================================
    ===========
    import java.util.*;
    import java.io.*;
    // Public class
    SetTestLauncher.======================================
    =======
    public class SetTestLauncher
    // Main method public static void main(String
    g args[]).===================
         public static void main(String args[])
    displayFile("test.txt"); // outputs result from
    om text file.
         // method to display a file on screen
         public static void displayFile (String textFile)
    // Instance
    ce
    variables.============================================
    ===
              // Creates new instances of SetOperations.
              SetOperations setA = new SetOperations();
              // Initialisation.
              String line = "", nextLine = "";
              FileReader fr = null;
              try
    // Opens the file with the FileReader data sink
    ink stream.
                   fr = new FileReader(textFile);
    // Converts the FileReader input stream with the
    the BufferedReader processing stream.
                   BufferedReader br = new BufferedReader(fr);
    // Iterates through text file reading lines until
    til end of text lines.
                   while (line != null)
    line = br.readLine(); // reads one line at a
    at a time.
    if(line == null) break; // when the line is null
    null break the loop.
                        // Creates a new instace of StringTokenizer.
                        StringTokenizer st = new StringTokenizer(line);
                        // Loops until there are no more tokens.
                        while (st.hasMoreTokens())
    String token = st.nextToken(); // reads next
    next token.
    // Only if the token encounters the String
    tring "membera".
                             if(token.equals("membera"))
                                  // *****THE PROBLEM LIES HERE....I GUESS
    // need to read the next line after encountering the word membera in text file
    nextLine = br.readLine(); // gets next line.
    setA.addMember(nextLine); // adds a member to
    ber to the set.
    // Displays members present in the set if
    set if vector is not empty.
                                  if (! setA.isSetEmpty())
                                       setA.printMember(); // print members present.
    // Displays the number of member/s present in
    ent in the vector.
    System.out.println("Number of set members: " +
    s: " + setA.countMember());
              // Catches and displays exceptions.
              catch (FileNotFoundException exp)
                   System.out.println(exp.getMessage());
                   exp.printStackTrace();
              catch (IOException exp)
                   System.out.println(exp.getMessage());
                   exp.printStackTrace();
              finally
                   try
                        // if file is found
                        if (fr != null)
                             // close file
                             fr.close();
                   catch (IOException exp)
                        exp.printStackTrace();
         } // end public static void main(String args[]).
    } // end public class SetTestLauncher.

  • Windows Easy Transfer (WET) Issues with External Hard Drive - "Can't read from the source file or disk"

    I work for Office Depot, in the tech department. Basically, one of our associates was supposed to do a data backup, and re-install Windows 7, then transfer the files back. He used Windows Easy Transfer and compacted everything into a 163 GB file. 
    Now comes the hard part. When we try to put it back on his computer ((drag-and-drop to the desktop) which has been wiped back to factory settings using the recovery partition), it stops at 79.5 GB remaining (you know how it doesn't give you a % of completion,
    it just shows how many GB are remaining) and then says "Can't read from the source file or disk" and gives you an option to try again, or cancel. It gets hung up on the same point each time.
    Normally, this wouldn't be a huge issue, but the contents on the drive are his wife's architect blueprints and interior design stuff, along with wedding photos, etc, which are the only copies they have. On top of those, they have court documents and other
    important files that we are unable to access now.
    I wasn't involved with this transfer, so I'm trying to clean up the mess as best I can. I remembered that the customer's wife was Russian, and had some files typed with a Russian keyboard, so on and so forth. I wonder if that's the issue? If not, I really
    have no idea how to manually extract things from a ".mig" file, or how to diagnose what area is potentially corrupted.
    In light of this situation, we tried using "Recuva" to recover the files post-wipe, but everything was corrupted or unable to be opened, and it also extracted and recovered all of the "useless" photos, such as the skype logos, up and
    down arrows for browsers, etc (it was 160,000+ photos).
    Trying to avoid a potential lawsuit, unhappy customer, and costing the company lots of money to see if professionals can get into this external hard drive.
    Other relevant information:
    We used a Toshiba 500 GB (465 GB) external hard drive.
    Customer's computer is an HP Pavilion P6000 Series (Model No. p6520y) running Windows 7 Home Premium 64-bit Service Pack 1.
    Any other information that is needed can be provided, thanks in advance, and hopefully we can find a solution to this issue quickly!
    -John

    I think there's a lack of understanding somewhere.
    "If you even can't start the process, please unplug it from your new PC. Then head back to your new computer and plug
    the external drive back in to your new computer. "
    Unplug from new, head back to new, plug it back in? That doesn't make much sense! Haha.
    I knew what you meant though, somewhat. When I search through the drives after clicking yes (Has windows easy transfer
    already saved your files blah blah blah) I click on the transfer file and it says "Windows Easy Transfer could not open the file".
    Rather than drag-and-drop the file to the desktop, I now tried to double-click on the file itself while it was plugged
    into the computer. It opened, and it started transferring until it was about 70% completed, and then an error popped up saying "WET can't open the easy transfer file, make sure your USB device is plugged in or check your internet connection". 
    I checked, and the USB hard drive's light wasn't on. Now, I unplug it and plug it back in, and the light comes back on,
    so I click Retry, and it resets the bar back to nothing and says "Transfer time: 1 minute".
    Rather than continue trying, I clicked "Cancel" instead of Retry, and it says "Your transfer did not complete successfully."
    It says to click "view report" for more information, but there's no "view report button".
    At the moment, I am scanning the External Drive for bad sectors using the check disk tool in properties. It's frozen
    at "0 USN bytes processed".

  • Problem with ArrayLists and writing and reading from a .dat file (I think)

    I'm brand new to this forum, but I'm sure hoping someone can help me with a problem I'm having with ArrayLists. This program was originally created with an array of objects that were displayed on a GUI with jtextFields, then cycling thru them via jButtons: First, Next, Previous, Last. Now I need to add the ability to modify, delete and add records. Both iterations of this program needed to write to and read from a .dat file.
    It worked just like it was suppose to when I used just the array, but now I need to use a "dynamic array" that will grow or shrink as needed: i.e. an ArrayList.
    When I aded the ArrayList I had the ArrayList use toArray() to fill my original array so I could continue to use all the methods I'd created for using with my array. Now I'm getting a nullPointerException every time I try to run my program, which means somewhere I'm NOT filling my array ???? But, I'm writing just fine to my .dat file, which is confusing me to no end!
    It's a long program, and I apologize for the length, but here it is. There are also 2 class files, a parent and 1 child below Inventory6. This was written in NetBeans IDE 5.5.1.
    Thank you in advance for any help anyone can give me!
    LabyBC
    package my.Inventory6;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import java.io.*;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.lang.IllegalStateException;
    import java.util.NoSuchElementException;
    import java.util.ArrayList;
    import java.text.NumberFormat;
    // Class Inventory6
    public class Inventory6 extends javax.swing.JFrame {
    private static InventoryPlusColor[] inventory;
    private static ArrayList inList;
    // create a tool that insure the specified format for a double number, when displayed
    private DecimalFormat doubleFormat = new DecimalFormat( "0.00" );
    private DecimalFormat singleFormat = new DecimalFormat( "0");
    // the index within the array of products of the current displayed product
    private int currentProductIndex;
    /** Creates new form Inventory6 */
    public Inventory6() {
    initComponents();
    currentProductIndex = 0;
    } // end Inventory6()
    private static InventoryPlusColor[] getInventory() {
    ArrayList<InventoryPlusColor> inList = new ArrayList<InventoryPlusColor>();
    inList.add(new InventoryPlusColor(1, "Couch", 3, 1250.00, "Blue"));
    inList.add(new InventoryPlusColor(2, "Recliner", 10, 525.00, "Green"));
    inList.add(new InventoryPlusColor(3, "Chair", 6, 125.00, "Mahogany"));
    inList.add(new InventoryPlusColor(4, "Pedestal Table", 2, 4598.00, "Oak"));
    inList.add(new InventoryPlusColor(5, "Sleeper Sofa", 4, 850.00, "Yellow"));
    inList.add(new InventoryPlusColor(6, "Rocking Chair", 2, 459.00, "Tweed"));
    inList.add(new InventoryPlusColor(7, "Couch", 4, 990.00, "Red"));
    inList.add(new InventoryPlusColor(8, "Chair", 12, 54.00, "Pine"));
    inList.add(new InventoryPlusColor(9, "Ottoman", 3, 110.00, "Black"));
    inList.add(new InventoryPlusColor(10, "Chest of Drawers", 5, 598.00, "White"));
    for (int j = 0; j < inList.size(); j++)
    System.out.println(inList);
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    return inventory;
    } // end getInventory() method
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jPanel1 = new javax.swing.JPanel();
    IDNumberLbl = new javax.swing.JLabel();
    IDNumberField = new javax.swing.JTextField();
    prodNameLbl = new javax.swing.JLabel();
    prodNameField = new javax.swing.JTextField();
    colorLbl = new javax.swing.JLabel();
    colorField = new javax.swing.JTextField();
    unitsInStockLbl = new javax.swing.JLabel();
    unitsInStockField = new javax.swing.JTextField();
    unitPriceLbl = new javax.swing.JLabel();
    unitPriceField = new javax.swing.JTextField();
    invenValueLbl = new javax.swing.JLabel();
    invenValueField = new javax.swing.JTextField();
    restockingFeeLbl = new javax.swing.JLabel();
    restockingFeeField = new javax.swing.JTextField();
    jbtFirst = new javax.swing.JButton();
    jbtNext = new javax.swing.JButton();
    jbtPrevious = new javax.swing.JButton();
    jbtLast = new javax.swing.JButton();
    jbtAdd = new javax.swing.JButton();
    jbtDelete = new javax.swing.JButton();
    jbtModify = new javax.swing.JButton();
    jbtSave = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    searchIDNumLbl = new javax.swing.JLabel();
    searchIDNumbField = new javax.swing.JTextField();
    jbtSearch = new javax.swing.JButton();
    searchResults = new javax.swing.JLabel();
    jbtExit = new javax.swing.JButton();
    jbtExitwoSave = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Inventory Program"));
    IDNumberLbl.setText("ID Number");
    IDNumberField.setEditable(false);
    prodNameLbl.setText("Product Name");
    prodNameField.setEditable(false);
    colorLbl.setText("Product Color");
    colorField.setEditable(false);
    colorField.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    colorFieldActionPerformed(evt);
    unitsInStockLbl.setText("Units In Stock");
    unitsInStockField.setEditable(false);
    unitPriceLbl.setText("Unit Price $");
    unitPriceField.setEditable(false);
    invenValueLbl.setText("Inventory Value $");
    invenValueField.setEditable(false);
    restockingFeeLbl.setText("5% Restocking Fee $");
    restockingFeeField.setEditable(false);
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(unitPriceLbl)
    .addComponent(unitsInStockLbl)
    .addComponent(colorLbl)
    .addComponent(prodNameLbl)
    .addComponent(IDNumberLbl)
    .addComponent(restockingFeeLbl)
    .addComponent(invenValueLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(IDNumberField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(prodNameField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(colorField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(invenValueField, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE))
    .addContainerGap())
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(IDNumberLbl)
    .addComponent(IDNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(prodNameLbl)
    .addComponent(prodNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(colorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(colorLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitsInStockLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitPriceLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(restockingFeeLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(invenValueField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(invenValueLbl))
    .addContainerGap())
    jbtFirst.setText("First");
    jbtFirst.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtFirstActionPerformed(evt);
    jbtNext.setText("Next");
    jbtNext.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtNextActionPerformed(evt);
    jbtPrevious.setText("Previous");
    jbtPrevious.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtPreviousActionPerformed(evt);
    jbtLast.setText("Last");
    jbtLast.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtLastActionPerformed(evt);
    jbtAdd.setText("Add");
    jbtAdd.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtAddActionPerformed(evt);
    jbtDelete.setText("Delete");
    jbtModify.setText("Modify");
    jbtModify.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtModifyActionPerformed(evt);
    jbtSave.setText("Save");
    jbtSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtSaveActionPerformed(evt);
    jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Search by:"));
    searchIDNumLbl.setText("Item Number:");
    jbtSearch.setText("Search");
    searchResults.setFont(new java.awt.Font("Tahoma", 1, 12));
    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(searchIDNumLbl)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(259, 259, 259)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jPanel2Layout.setVerticalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(searchIDNumLbl)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(32, 32, 32)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtSearch)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jbtExit.setText("Save and Exit");
    jbtExit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitActionPerformed(evt);
    jbtExitwoSave.setText("Exit");
    jbtExitwoSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitwoSaveActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
    .addComponent(jbtExitwoSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jbtExit)))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtFirst)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtNext)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtPrevious)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtLast))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(12, 12, 12)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtAdd)
    .addComponent(jbtDelete)
    .addComponent(jbtModify)
    .addComponent(jbtSave))))
    .addContainerGap())
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtFirst, jbtLast, jbtNext, jbtPrevious});
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtAdd, jbtDelete, jbtModify, jbtSave});
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(21, 21, 21)
    .addComponent(jbtAdd)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtDelete)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtModify)
    .addGap(39, 39, 39)
    .addComponent(jbtSave))
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jbtFirst)
    .addComponent(jbtNext)
    .addComponent(jbtPrevious)
    .addComponent(jbtLast))
    .addGap(15, 15, 15)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtExit)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtExitwoSave)))
    .addContainerGap())
    pack();
    }// </editor-fold>
    private void jbtExitwoSaveActionPerformed(java.awt.event.ActionEvent evt) {                                             
    System.exit(0);
    private void jbtSaveActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String prodNameMod, colorMod;
    double unitsInStockMod, unitPriceMod;
    int idNumMod;
    idNumMod = Integer.parseInt(IDNumberField.getText());
    prodNameMod = prodNameField.getText();
    unitsInStockMod = Double.parseDouble(unitsInStockField.getText());
    unitPriceMod = Double.parseDouble(unitPriceField.getText());
    colorMod = colorField.getText();
    if(currentProductIndex == inventory.length) {
    inList.add(new InventoryPlusColor(idNumMod, prodNameMod,
    unitsInStockMod, unitPriceMod, colorMod));
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    } else {
    inventory[currentProductIndex].setIDNumber(idNumMod);
    inventory[currentProductIndex].setProdName(prodNameMod);
    inventory[currentProductIndex].setUnitsInStock(unitsInStockMod);
    inventory[currentProductIndex].setUnitPrice(unitPriceMod);
    inventory[currentProductIndex].setColor(colorMod);
    displayProduct(inventory[currentProductIndex]);
    private static void writeInventory(InventoryPlusColor i,
    DataOutputStream out) {
    try {
    out.writeInt(i.getIDNumber());
    out.writeUTF(i.getProdName());
    out.writeDouble(i.getUnitsInStock());
    out.writeDouble(i.getUnitPrice());
    out.writeUTF(i.getColor());
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception writing data",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } //end writeInventory()
    private static DataOutputStream openOutputStream(String name) {
    DataOutputStream out = null;
    try {
    File file = new File(name);
    out =
    new DataOutputStream(
    new BufferedOutputStream(
    new FileOutputStream(file)));
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error", "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return out;
    } // end openOutputStream()
    private static void closeFile(DataOutputStream out) {
    try {
    out.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeFile()
    private static DataInputStream getStream(String name) {
    DataInputStream in = null;
    try {
    File file = new File(name);
    in = new DataInputStream(
    new BufferedInputStream(
    new FileInputStream(file)));
    } catch (FileNotFoundException e) {
    JOptionPane.showMessageDialog(null, "The file doesn't exist",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error creating file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return in;
    private static void closeInputFile(DataInputStream in) {
    try {
    in.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeInputFile()
    private double entireInventory() {
    // a temporary double variable that the method will return ...
    // after each product's inventory is added to it
    double entireInventory = 0;
    // loop to control number of products
    for (int index = 0; index < inventory.length; index++) {
    // add each inventory to the entire inventory
    entireInventory += inventory[index].setInventoryValue();
    } // end loop to control number of products
    return entireInventory;
    } // end method entireInventory
    private void jbtLastActionPerformed(java.awt.event.ActionEvent evt) {                                       
    currentProductIndex = inventory.length-1; // move to the last product
    // display the information for the last product
    displayProduct(inventory[currentProductIndex]);
    private void jbtPreviousActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if (currentProductIndex != 0) // it's not the first product displayed
    currentProductIndex -- ; // move to the previous product (decrement the current index)
    } else // the first product is displayed
    currentProductIndex = inventory.length-1; // move to the last product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtNextActionPerformed(java.awt.event.ActionEvent evt) {                                       
    if (currentProductIndex != inventory.length-1) // it's not the last product displayed
    currentProductIndex ++ ; // move to the next product (increment the current index)
    } else // the last product is displayed
    currentProductIndex = 0; // move to the first product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtFirstActionPerformed(java.awt.event.ActionEvent evt) {                                        
    currentProductIndex = 0;
    // display the information for the first product
    displayProduct(inventory[currentProductIndex]);
    private void colorFieldActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    private void jbtModifyActionPerformed(java.awt.event.ActionEvent evt) {                                         
    prodNameField.setEditable(true);
    prodNameField.setFocusable(true);
    unitsInStockField.setEditable(true);
    unitPriceField.setEditable(true);
    private void jbtAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
    IDNumberField.setText("");
    IDNumberField.setEditable(true);
    prodNameField.setText("");
    prodNameField.setEditable(true);
    colorField.setText("");
    colorField.setEditable(true);
    unitsInStockField.setText("");
    unitsInStockField.setEditable(true);
    unitPriceField.setText("");
    unitPriceField.setEditable(true);
    restockingFeeField.setText("");
    invenValueField.setText("");
    currentProductIndex = inventory.length;
    private void jbtExitActionPerformed(java.awt.event.ActionEvent evt) {                                       
    DataOutputStream out = openOutputStream("inventory.dat");
    for (InventoryPlusColor i : inventory)
    writeInventory(i, out);
    closeFile(out);
    System.exit(0);
    private static InventoryPlusColor readProduct(DataInputStream in) {
    int idNum = 0;
    String prodName = "";
    double inStock = 0.0;
    double pric

    BalusC -- The line that gives me my NullPointerException is when I call the "DisplayProduct()" method. Its a dumb question, but with NetBeans how do I find out which reference could be null? I'm not very familiar with how NetBeans works with finding out how to debug. Any help you can give me would be greatly appreciated.The IDE is com-plete-ly irrelevant. It's all about the source code.
    Do you understand anyway when and why a NullPointerException is been thrown? It is a subclass of RuntimeException and those kind of exceptions are very trival and generally indicate an design/logic/thinking fault in your code.
    SomeObject someObject = null; // The someObject reference is null.
    someObject.doSomething(); // Invoking a reference which is null would throw NPE.

  • HOW TO WRITE AND READ FROM A TEXT FILE???

    How can I read from a text file and then display the contents in a JTextArea??????
    Also how can I write the contents of a JTextArea to a text file.
    Extra Question::::::: Is it possible to write records to a text file. If you have not idea what I am talking about then ignore it.
    Manny thanks,
    your help is much appreciated though you don't know it!

    Do 3 things.
    -- Look through the API at the java.io package.
    -- Search previous posts for "read write from text file"
    -- Search java.sun.com for information on the java.io package.
    That should clear just about everything up. If you have more specific problems, feel free to come back and post them.

  • How to read from a text file one character at a time?

    Hello
    I wish to read from a text file in a for loop and that on every iteration i read one charachter and proceed to the next one.
    can anyone help me?
    Lavi 

    lava wrote:
    I wish to read from a text file in a for loop and that on every iteration i read one charachter and proceed to the next one.
    can anyone help me?
    Some additional comments:
    You really don't want to read any file one character at a time, because it is highly inefficient. More typically, you read the entire file into memory with one operation (or at least a large chunk, if the file is gigantic) and then do the rest of the operations in memory.  One easy way to analyze it one byte at a time would be to use "string to byte array" and then autoindex into a FOR loop, for example.
    Of course you could also read the file directly as a U8 array instead of a string.
    Message Edited by altenbach on 06-10-2008 08:57 AM
    LabVIEW Champion . Do more with less code and in less time .

  • Problem parsing XML with schema when extracted from a jar file

    I am having a problem parsing XML with a schema, both of which are extracted from a jar file. I am using using ZipFile to get InputStream objects for the appropriate ZipEntry objects in the jar file. My XML is encrypted so I decrypt it to a temporary file. I am then attempting to parse the temporary file with the schema using DocumentBuilder.parse.
    I get the following exception:
    org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element '<root element name>'
    This was all working OK before I jarred everything (i.e. when I was using standalone files, rather than InputStreams retrieved from a jar).
    I have output the retrieved XML to a file and compared it with my original source and they are identical.
    I am baffled because the nature of the exception suggests that the schema has been read and parsed correctly but the XML file is not parsing against the schema.
    Any suggestions?
    The code is as follows:
      public void open(File input) throws IOException, CSLXMLException {
        InputStream schema = ZipFileHandler.getResourceAsStream("<jar file name>", "<schema resource name>");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
          factory.setNamespaceAware(true);
          factory.setValidating(true);
          factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
          factory.setAttribute(JAXP_SCHEMA_SOURCE, schema);
          builder = factory.newDocumentBuilder();
          builder.setErrorHandler(new CSLXMLParseHandler());
        } catch (Exception builderException) {
          throw new CSLXMLException("Error setting up SAX: " + builderException.toString());
        Document document = null;
        try {
          document = builder.parse(input);
        } catch (SAXException parseException) {
          throw new CSLXMLException(parseException.toString());
        }

    I was originally using getSystemResource, which worked fine until I jarred the application. The problem appears to be that resources returned from a jar file cannot be used in the same way as resources returned directly from the file system. You have to use the ZipFile class (or its JarFile subclass) to locate the ZipEntry in the jar file and then use ZipFile.getInputStream(ZipEntry) to convert this to an InputStream. I have seen example code where an InputStream is used for the JAXP_SCHEMA_SOURCE attribute but, for some reason, this did not work with the InputStream returned by ZipFile.getInputStream. Like you, I have also seen examples that use a URL but they appear to be URL's that point to a file not URL's that point to an entry in a jar file.
    Maybe there is another way around this but writing to a file works and I set use File.deleteOnExit() to ensure things are tidied afterwards.

  • HELP ME! Creating a table from a data file

    Hi
    I'm writing an application for data visualization. The user can press the "open file" button and a FileChooser window will come up where the user can select any data file. I would like to take that data file and display it as a table with rows and columns. The user needs to be able to select the coliumns to create a graph. I have tried many ways to create a table, but nothing seems to work! Can anyone help me?! I just want to read from the data file and create a spreadsheet type table... I won't know how many rows and columns I'll need in advance, so the table needs to be dynamic!
    If you have ANY tips, I'd REALLY appreciated.....

    I won't know how many rows and columns I'll need in advance, so the table needs to be dynamic!You may use a List (ArrayList, LinkedList or Vector) for that.
    Lists allow you (dynamically) add elements.

  • Read images from external jar file (Sun's Java L&F Graphics repository)

    Hi!
    I don't know how to read images from an external jar file. Sun has a Java Look and Feel graphics repository that contains a lot of good images that can be used on buttons and so on. This repository is delivered as a jar file, containing only images, and I want to read the image files from that jar file directly without including them inside my application jar file. The application and image jar files will be in the same directory.
    I have absolutely no clue how to solve this. Is it necessary to include the images inside my application jar file or is it possible to have them separate as I want.
    Would really appreciate some help!
    Best regards
    Lars

    Hi,
    There is two ways :
    1) Add your jarfile to the classpath.
    Use the class loader :
    URL url = ClassLoader.getSystemResource("your/package/image.gif");
    Image im = (new ImageIcon(url)).getImage();
    or
    Image im = Toolkit.getDefaultToolkit().getImage(url);2)If you don't want to add the jar to the classpath you can use this (under jdk 1.4):
    import java.util.*;
    import java.util.jar.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class ImageUtilities {
         public static Image getImage(String jarFileName, String fileName) {
              BufferedImage image = null;
              try {
                   JarFile jar = new JarFile(new File(jarFileName), false, JarFile.OPEN_READ);
                   JarEntry entry = jar.getJarEntry(fileName);
                   BufferedInputStream stream = new BufferedInputStream(jar.getInputStream(entry));
                   image = ImageIO.read(stream) ;
              catch (Exception ex) {
                   System.out.println(ex);
              return(image);
    }I hope this helps,
    Denis

  • Read from a config file in File Adapter in SOA Suite 11g

    I want to read from a config file in order to determine whether to archive or delete the file after processing using file adapter in SOA Suite 11g. How do i do that.

    only part i replied on was the part of how to read a file
    but i think in your case you could do the next
    use the sync file adapter to read in the file during your process
    based on this content you set a variable "myOutputDirectory"
    then create a file adapter (write) which will store the file on file system
    http://docs.oracle.com/cd/E23943_01/integration.1111/e10231/adptr_file.htm#CIACICFD
    4.3.2.2.5 Specifying a Dynamic Outbound File Name
    and use that (jca.file.Directory) property to store the file either on the archive location or the delete location

  • Cannot read from the source file or disk

    I had to get a new hard drive for my Satellite A665 old one kept freezing up; had a recovey disk from Geek Squad when I got it but they did not work.  So I ordered a Recovery Disc set from Toshiba. 
    A few minutes after I insert the 3nd disc, I get the following message:
    Cannot read from the source file or disk
    PREINST14.SWM
    Type: SWM File
    Size:  670 MB
    Modified: 10/29/2010 11:24pm
    Clicking [Try Again] or [Skip] clicked try again twice. Gave same message so clicked skip. Got another message.
    Cannot read from the source file or disk
    PREINST18.SWM
    Type: SWM File
    Size:  372 MB
    Modified: 10/29/2010 11:24pm
    Clicking [Try Again] or [Skip] clicked try again twice. Gave same message so clicked skip after checking do it for next one. Got error message.
    An error has occurred.
    Error:  10-FC06-0002
    Recovery Error.
    Please press [OK] to turn off the computer.
    I tried erasing the disk, then running the Recovery Wizard again, but wind up in the same place.

    It's hard to know exactly what the problem is. You might want to contact customer support because it could just be a faulty disc.
    - Peter

Maybe you are looking for

  • I can't install any adobe programs!!!

    Dear support! My problem is I can't install the Adobe programs from creative cloud. The story: When I try installing the premiere cs6 family the program dowloading, but not extract. Then I wrote a email the hungarian adobe distributor (designshop.hu)

  • Contracts open interface in R12?

    Hi, In past(11.5.9) we've used APIs for interfacing legacy contracts. Now that we're on R12.1.1, I was wondering if there exists an open interface for Contracts. TIA Alka

  • Allow movement of split location in before/after comparison

    It would save me a lot of time if the before/after split location was movable. If I'm developing a portrait of two people, the split usually goes right between the two people, so I can't get a good feel for how the after affect "the other" person. Al

  • When is new version of i mac due for release

    When is new version of I mac due for release

  • Mac pro turned off by itself

    i do most of my work on a mac pro (1,1) and this evening at precisely 8:04pm my mac pro clicked and then turned off the computer did not shut down, it just turned off i should note that the click i heard was the same as the one that i hear when i fir