-4

I am trying to output an XML String into a .xml file for debugging purpose. My String looks like this:

System.out.println("xmlString = \n" + xmlString);
===========================================================
INFO: xmlString = 
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader">
  <int name="status">0</int>
  <int name="QTime">2</int>
  <lst name="params">
    <str name="indent">true</str>
    <str name="q">source_t:ST</str>
    <str name="wt">xml</str>
  </lst>
</lst>
...

Now, the following code is to output the String into XML file.

try {
                System.out.println("Writing xmlString to xml file");

                File file = new File("xmlString.xml");

                // if file doesnt exists, then create it
                if (!file.exists()) {
                        file.createNewFile();
                }

                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(xmlString);
                bw.close();

                System.out.println("Done writing file");

        } catch (IOException e) {
                e.printStackTrace();
        }

But this is the error I got from output log:

INFO: Writing xmlString to xml file
INFO: Done writing file
SEVERE: java.net.MalformedURLException: no protocol: <?xml version="1.0" encoding="UTF-8"?>

No file is created. Can someone tell me what does this mean? And how to solve this? Thanks in advance

====================================================================================== Edit (I initially though that the error lies at the FileWritter, which is why I didn't post the whole code): I have edited my post to display my whole code. This code is actually called by a JSP file. Which passes the xmlString

public class SAXParserClass {

    //Declare as public since it needs to be redefined for appending into ArrayList
    public static String row[] = new String[5];         //id, full_message_t, source_t, news_t, link_t  

    public ArrayList<String[]> XMLReader(String xmlString)
    {
        //Output: GlassFish Server. Test if String is passed in correctly
        System.out.println("xmlString = \n" + xmlString);
        try {
                System.out.println("Writing xmlString to xml file");

                File file = new File("xmlString.xml");

                // if file doesnt exists, then create it
                if (!file.exists()) {
                        file.createNewFile();
                }

                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(xmlString);
                bw.close();

                System.out.println("Done writing file");

        } catch (IOException e) {
                e.printStackTrace();
        }

          //Declaration
          final ArrayList<String[]> tableResult = new ArrayList<String[]>();    //Store ArrayList of row[]

          try {

              SAXParserFactory factory = SAXParserFactory.newInstance();
              SAXParser saxParser = factory.newSAXParser();

              DefaultHandler handler = new DefaultHandler() 
              {
                  //When these are TRUE, extract the content
                    boolean b_id = false;
                    boolean b_full_message_t = false;
                    boolean b_source_t = false;
                    boolean b_news_t = false;
                    boolean b_link_t = false;                

                    //############################################################################################
                    //Look for <start> tags
                    public void startElement(String uri, String localName,String qName, 
                            Attributes attributes) throws SAXException {

                            System.out.println("Start Element :" + qName);

                            //Only interested in <str>
                            if (qName.equalsIgnoreCase("str")) {
                                String name = attributes.getValue("name");

                                    //Check for name="id"
                                if(name.equalsIgnoreCase("id")){
                                    b_id = true;
                                }                                
                                    //Check for name="full_message_t"
                                else if(name.equalsIgnoreCase("full_message_t")){
                                    b_full_message_t = true;
                                }
                                else if(name.equalsIgnoreCase("source_t")){
                                    b_source_t = true;
                                }
                                else if(name.equalsIgnoreCase("news_t")){
                                    b_news_t= true;
                                }
                                else if(name.equalsIgnoreCase("link_t")){
                                    b_link_t = true;
                                }                             
                            }//end if

                    }//end startElement

                    //############################################################################################
                    //Look for <end> tags
                    public void endElement(String uri, String localName,
                            String qName) throws SAXException {

                            System.out.println("End Element :" + qName);

                            //When reach </doc>, row Array is complete. Add into ArrayList
                            if (qName.equalsIgnoreCase("doc")) {
                                    System.out.println("Push row into Arraylist : " + row[0]);
                                    tableResult.add(row);
                                    row = new String[5];    //reinitialize String[]
                            }
                    }//end endElement

                    //############################################################################################
                    //Get the content
                    public void characters(char ch[], int start, int length) throws SAXException {

                            if (b_id) {
                                    //System.out.println("id : " + new String(ch, start, length));
                                    row[0] = new String(ch, start, length);
                                    System.out.println("The id is " + row[0]);
                                    b_id = false;
                            }
                            else if (b_full_message_t) {
                                    //System.out.println("fullmsg : " + new String(ch, start, length));
                                    row[1] = new String(ch, start, length);
                                    System.out.println("The fullmsg is " + row[1]);
                                    b_full_message_t = false;
                            }
                            else if (b_source_t) {
                                    //System.out.println("fullmsg : " + new String(ch, start, length));
                                    row[2] = new String(ch, start, length);
                                    System.out.println("The source is " + row[2]);
                                    b_source_t = false;
                            }
                            else if (b_news_t) {
                                    //System.out.println("fullmsg : " + new String(ch, start, length));
                                    row[3] = new String(ch, start, length);
                                    System.out.println("The news is " + row[3]);
                                    b_news_t = false;
                            }
                            else if (b_link_t) {
                                    //System.out.println("fullmsg : " + new String(ch, start, length));
                                    row[4] = new String(ch, start, length);
                                    System.out.println("The link is " + row[4]);
                                    b_link_t = false;
                            }

                    }//end characters

           };//end DefaultHandler

              //############################################################################################
              //Read the String  
              //saxParser.parse("solrTest.xml", handler);
              //File file = new File("solrTest.xml");
              //InputStream inputStream= new FileInputStream(file);
//            Reader reader = new InputStreamReader(xmlString,"UTF-8");
// 
//            InputSource is = new InputSource(reader);
//            is.setEncoding("UTF-8");

              saxParser.parse(xmlString, handler);

           } catch (Exception e) {
             e.printStackTrace();
           }

          //Test output Arraylist
          System.out.println("Test Result!!!");

          for(String[] columns : tableResult){
              for(int i=0; i<columns.length; i++){
                  System.out.println("Number = " + columns[i]);
              }
          }

          //Return the ArrayList of String[]          
          return tableResult;
      }//end XMLReader

}//end class
user2741620
  • 305
  • 2
  • 7
  • 21
  • It should be obvious that that exception isn't thrown by that code. It's thrown by something afterwards, as the stack trace will show. NB the createNewFile() and getAbsolutePath() calls are both redundant. – user207421 Apr 12 '14 at 07:18
  • Note that `.createNewFile()` won't fail with an IOException if it fails, you have to check the return code (a boolean!). Also, if you use Java 7, create a `Path` and use `Files.newBufferedWriter()` instead (and use a try-with-resources statement) – fge Apr 12 '14 at 07:22
  • @fge He doesn't even need to call it, let alone check the result. – user207421 Apr 12 '14 at 07:23
  • This code is working fine for me. Where does these errors are getting it from dont know. – Raju Sharma Apr 12 '14 at 07:35
  • @OP Somewhere lower down in your code you are using this XML string as a URL. It isn't a URL. The exception says it all. – user207421 Apr 12 '14 at 08:03
  • Below this code, I have an SAXParser that is suppose to take the xmlString and convert each content to ArrayList of String Array. I don't believe I am using xmlString as URL whatsoever. – user2741620 Apr 12 '14 at 08:58
  • Hi. I have added the full code. – user2741620 Apr 12 '14 at 09:09

1 Answers1

6

saxParser.parse(xmlString, handler);

The problem is here. You are passing the XML string as though it was a URL. It isn't. You need to read the Javadoc for SAXParser.parse().

Note:

  1. You posted the wrong code. The stack trace told you where the exception was thrown from. You evidently didn't even look at it.
  2. You failed to answer questions when they were asked.
  3. You asked irrelevant questions.
  4. You denied doing the very thing that caused the problem, after it was suggested that's what you must be doing. So you didn't even check.

This is not a rational strategy for solving problems.

user207421
  • 305,947
  • 44
  • 307
  • 483