Results 1 to 4 of 4
  1. #1
    coolman50544 is offline Member
    Join Date
    Apr 2014
    Location
    Miami, FL
    Posts
    47
    Rep Power
    0

    Angry My Java code removed the data from my XML file.

    I tried working with XML today, since that's what my book teaches. First, I read some data about Product objects that are suppose to represent products with a code, description, and price. That worked fine. Then, I tried creating a writeProducts(ArrayList<Product> products) method, and man it did not go well.

    How it works is that there is an ArrayList instance variable in the class that keeps track of all of my products after the readProducts method returns that ArrayList from the XML file. When I ran the method I had a lot of stack traces printed. I then checked the file on a web browser and an editor, and saw it was completely empty.

    I would like two things from you guys.

    1. Why did this happen?
    2. How can I fix this?

    Here's the code:
    Java Code:
    import java.util.ArrayList;
    import java.io.*;
    import javax.xml.stream.*;  // StAX API
    
    public class XMLTesterApp
    {
        private static String productsFilename = "products.xml";
    
        public static void main(String[] args)
        {
            System.out.println("Products list:");
            ArrayList<Product> products = readProducts();
            printProducts(products);
    
    
            Product p1 = new Product("test", "XML Tester", 77.77);
            products.add(p1);
            writeProducts(products);
            System.out.println("XML Tester has been added to the XML document.\n");
    
    
            System.out.println("Products list:");
            products = readProducts();
            printProducts(products);
    
    
            products.remove(2);
            writeProducts(products);
            System.out.println("XML Tester has been deleted from the XML document.\n");
    
    
            System.out.println("Products list:");
            products = readProducts();
            printProducts(products);
    
        }
    
        private static ArrayList<Product> readProducts()
        {
            ArrayList<Product> products = new ArrayList<>();
            Product p = null;
            XMLInputFactory inputFactory = XMLInputFactory.newFactory();
            
            try {
                XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileReader(productsFilename));
              
                while(reader.hasNext()) {
                    int eventType = reader.getEventType();
                    switch(eventType) {
                        case XMLStreamConstants.START_ELEMENT:
                            String elementName = reader.getLocalName();
                            if(elementName.equals("Product")) {
                                p = new Product();
                                String code = reader.getAttributeValue(0);
                                p.setCode(code);
                            }
                            if(elementName.equals("Description")) {
                                String description = reader.getElementText();
                                p.setDescription(description);
                            }
                            if(elementName.equals("Price")) {
                                String priceString = reader.getElementText();
                                double price = Double.parseDouble(priceString);
                                p.setPrice(price);
                            }
                            break;
                        case XMLStreamConstants.END_ELEMENT:
                            if(reader.getLocalName().equals("Product")) {
                                products.add(p);
                            }
                            break;
                        default:
                            break;
                    }
                    reader.next();
                }       
    
            }
            catch(IOException | XMLStreamException e){
                e.printStackTrace();
            }
            return products;
        }
    
        private static void writeProducts(ArrayList<Product> products)
        {
            XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
            
            try {
                XMLStreamWriter writer = outputFactory.createXMLStreamWriter(new FileWriter(productsFilename));
                
                writer.writeStartDocument("1.0");
                writer.writeComment("Product data");
                writer.writeStartElement("Products");
                for(Product p : products) {
                    writer.writeStartElement("Product");
                    writer.writeAttribute("Code", p.getCode());
                    writer.writeStartElement("Description");
                    writer.writeCharacters(p.getDescription());
                    writer.writeEndElement();
                    writer.writeStartElement("Price");
                    writer.writeCharacters(Double.toString(p.getPrice()));
                    writer.writeEndElement();
                    writer.writeEndElement();
                }
                writer.writeEndElement();
            }
            catch(IOException | XMLStreamException e) {
                e.printStackTrace();
            }
        }
    
        private static void printProducts(ArrayList<Product> products)
        {
            for (Product p : products)
            {
                printProduct(p);
            }
            System.out.println();
        }
    
        private static void printProduct(Product p)
        {
            String productString =
                StringUtils.padWithSpaces(p.getCode(), 8) +
                StringUtils.padWithSpaces(p.getDescription(), 44) +
                p.getFormattedPrice();
    
            System.out.println(productString);
        }
    }
    Here's the stack trace
    Java Code:
    ant -f C:\\Users\\alfonso\\Downloads\\javp_allfiles\\java\\netbeans\\ex_starts\\ch19_ex1_XMLTester -Dnb.internal.action.name=run run
    init:
    Deleting: C:\Users\alfonso\Downloads\javp_allfiles\java\netbeans\ex_starts\ch19_ex1_XMLTester\build\built-jar.properties
    deps-jar:
    Updating property file: C:\Users\alfonso\Downloads\javp_allfiles\java\netbeans\ex_starts\ch19_ex1_XMLTester\build\built-jar.properties
    Compiling 1 source file to C:\Users\alfonso\Downloads\javp_allfiles\java\netbeans\ex_starts\ch19_ex1_XMLTester\build\classes
    warning: [options] bootstrap class path not set in conjunction with -source 1.7
    1 warning
    compile:
    run:
    Products list:
    
    javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
    Message: Premature end of file.
    	at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:601)
    	at XMLTesterApp.readProducts(XMLTesterApp.java:75)
    XML Tester has been added to the XML document.
    
    Products list:
    
    	at XMLTesterApp.main(XMLTesterApp.java:12)
    javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
    Message: Premature end of file.
    	at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:601)
    	at XMLTesterApp.readProducts(XMLTesterApp.java:75)
    	at XMLTesterApp.main(XMLTesterApp.java:23)
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
    	at java.util.ArrayList.rangeCheck(ArrayList.java:638)
    	at java.util.ArrayList.remove(ArrayList.java:477)
    	at XMLTesterApp.main(XMLTesterApp.java:27)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)
    On a side note, is it normal if almost everything I writer has to be debugged? That seems to be the case with me

  2. #2
    coolman50544 is offline Member
    Join Date
    Apr 2014
    Location
    Miami, FL
    Posts
    47
    Rep Power
    0

    Default Re: My Java code removed the data from my XML file.

    Nevermind, fixed the code. I just added writer.flush() and writer.close() methods at the end of my writer class.

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: My Java code removed the data from my XML file.

    Quote Originally Posted by coolman50544 View Post
    On a side note, is it normal if almost everything I writer has to be debugged? That seems to be the case with me
    Yes, it's perfectly normal.
    It doesn't take much to put a simple bug (usually via a copy/paste) into your code, no matter how much experience you have.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,354
    Rep Power
    6

    Default Re: My Java code removed the data from my XML file.

    "If it isn't tested, it's broken."

    I don't know how many times I have proven that statement and I've seen it proven.

    PS: close() also does a flush().
    Last edited by gimbal2; 07-17-2014 at 10:31 AM.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Widget Issue (link removed)
    By soundprizm in forum New To Java
    Replies: 4
    Last Post: 04-22-2011, 03:25 AM
  2. Replies: 1
    Last Post: 03-29-2011, 09:59 AM
  3. Using Tokenizer to parse file data--CODE
    By Cylab in forum Java Software
    Replies: 0
    Last Post: 07-26-2010, 12:48 PM
  4. Data Sorting in a .data file using java
    By stutiger99 in forum New To Java
    Replies: 2
    Last Post: 10-08-2008, 03:52 AM
  5. when objects are removed from heap
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-09-2007, 05:25 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •