2011-06-02 111 views
0

我有这段代码给出SAXParseError,即它没有获取内容,但是当我在我的测试pg中使用它时,它的作用是正确的。这里我提供我的原代码块,可以ANY1弄清楚是什么问题org.xml.sax.SAXParseException:文件过早结束

这是部分地方I fetch a xml and append a node to it但似乎我不能够得到文件本身

String atemp=readFileAsString("../webapps/abc/include/xml/data.xml") 

     log.info("ok thats good") 

     String[] splitString=res.split(",") 

     log.info(atemp) 

     try 
     { 
      def root = new XmlSlurper().parseText(atemp) 
     } 
     catch(Exception e) 
     { 
      log.debug("parse errror: "+e) 
     } 
     root.appendNode { 
      row { 
      name(splitString[1]) 
      host(splitString[2]) 
      desc(splitString[3]) 
      product(splitString[4]) 
      type(splitString[5]) 
      time(splitString[6]) 
      by(splitString[7]) 
      } 
     } 

     def outputBuilder = new StreamingMarkupBuilder() 
     String temp = outputBuilder.bind{ mkp.yield root } 

     File file = new File("../webapps/abc/include/xml/data.xml"); 
     BufferedWriter output = new BufferedWriter(new FileWriter(file)); 
     output.write(temp); 
     output.close(); 
     log.info(temp) 

readFileAsString功能

​​

输出

INFO http-5050-Processor24 com.abc.helper.WriteXml - false 
INFO http-5050-Processor24 com.abc.helper.WriteXml - File Content 
INFO http-5050-Processor24 com.abc.helper.WriteXml - ok thats good 

注意:我能够打开该文件在我的测试程序具有相同路径

+0

您的'readFileAsString'不考虑[文档编码](http://www.w3.org/TR/xml/#sec-guessing)。 – McDowell 2011-06-02 10:17:22

回答

1

假设这是在Groovy中,我相信你可以替换所有代码:

File f = new File('../webapps/abc/include/xml/data.xml') 
def root = new XmlSlurper().parse(f) 
String[] splitString = res.split(',') 
root.appendNode { 
    row { 
    name(splitString[1]) 
    host(splitString[2]) 
    desc(splitString[3]) 
    product(splitString[4]) 
    type(splitString[5]) 
    time(splitString[6]) 
    by(splitString[7]) 
    } 
} 
def outputBuilder = new StreamingMarkupBuilder() 
String newXml = outputBuilder.bind{ mkp.yield root } 
f.text = newXml 

但我重复,在web应用程序中这样做可能是一个坏主意,就好像两个线程同时调用此代码一样,文件将变得不可预知(并且由于它变得更大,所以更多不可预知)

此外,您可能需要更改:

File f = new File('../webapps/abc/include/xml/data.xml') 

File f = new File("${System.properties['catalina.base']}/webapps/abc/include/xml/data.xml") 

至于建议您in a previous question of yours

+0

:tim:f.text = newXml是做什么的? – abi1964 2011-06-02 10:18:14

+1

@Abhishek用字符串'newXml'的内容覆盖文件'f'中的文本...参见[文档](http://groovy.codehaus.org/groovy-jdk/java/io/File。 HTML#的setText%28java.lang。字符串%29) – 2011-06-02 10:20:56

+0

谢谢蒂姆:)解决了我的问题 – abi1964 2011-06-02 10:35:36

0

readFileAsString方法看起来不错,但如果日志输出到信那么你的应用程序正在读取一个空文件,这就是导致XML解析异常的原因。

首先要检查的是您尝试读取的文件的路径名实际上是正确的,并且该位置的文件实际上不是空的。尝试在readFileAsString

log.info("file size is " + new File(filePath).length()); 

注意,零表示开始加入这一行无论是文件不存在,或者它是空的。在代码的其余部分


看,你的应用程序似乎是读取文件,做一些它,然后写回同一个地方。考虑它是生成输出的代码被破坏的可能性......并且您的应用程序试图读取和解析先前已被破坏的文件。