使用FileInputStream读取xml文件

发布于 2024-11-30 14:27:16 字数 4060 浏览 0 评论 0原文

我正在使用下面给出的代码读取 XML 文件,但每次我读取 XML 并打印相同的 XML 的开始标记总是缺失,这又会产生错误。

读取 xml 的代码:

package com.vaannila.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.vaannila.FormBean.XmlRetrivalForm;

public class AppletRefeshAction  extends Action {
    String filepath = "C:/Users/ashutosh_k/idoc/docRuleTool/WebContent/data/Malaria.xml";
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        XmlRetrivalForm xrf = (XmlRetrivalForm)form;
        String dieasename =xrf.getDieseasename();
        System.out.println("ghhjhhjkh"+dieasename);
        /* this part of the code is from jsp */
        //FileReader fis = new FileReader(new File(filepath));
        FileInputStream fis = new FileInputStream(new File(filepath));
        byte bin[] = new byte[(int) new File(filepath).length()];
        while(fis.read()>0){
        fis.read(bin);
        }
        System.out.println("I am here after reading the xml part of it ");
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.getOutputStream().write(bin);
//      response.getWriter().write(bin);
        String ashu = new String(bin);
        String iam =ashu.trim();
        System.out.println("i am in the new action class now ");
        System.out.println(iam);
        fis.close();
        /* this part of the code jsp ends here */
        return null;
    }

}

生成的输出 xml:

?xml version="1.0" encoding="UTF-8" standalone="no"?><tree>
<declarations>
    <attributeDecl name="name" type="String"/>
</declarations>
<branch>
<branch>
<attribute name="name" value="Excess Stool"/>
<branch>
<branch>
<attribute name="name" value="Do you have this condition for more than a weeks time"/>
<branch>
<attribute name="name" value=""/></branch>
<branch>
<attribute name="name" value=""/></branch>
</branch>
<branch>
<attribute name="name" value="No"/></branch>
<attribute name="name" value="Do you have watery stool"/></branch>
<branch>
<attribute name="name" value="No"/></branch>
</branch>
<branch>
<branch>
<attribute name="name" value="Was your peak temperature greater than 104"/>
<branch>
<branch>
<attribute name="name" value="Do you have chills"/>
</branch>
<branch>
<attribute name="name" value="No"/></branch>
<attribute name="name" value="Do you have high fever for more than a weeks time "/></branch>
<branch>
<attribute name="name" value="No"/></branch>
</branch>
<branch>
<attribute name="name" value="No"/></branch>
<attribute name="name" value="High Fever"/></branch>
<branch>
<branch>
<attribute name="name" value="Do you have pain in the left part of the head "/>
<branch>
<branch>
<attribute name="name" value="Duration of the headache spans for more than a day "/>
</branch>
<branch>
<attribute name="name" value="No"/></branch>
<attribute name="name" value="Do you have headache more than 5 times a day "/></branch>
<branch>
<attribute name="name" value="No"/></branch>
</branch>
<branch>
<attribute name="name" value="No"/></branch>
<attribute name="name" value="Bodyache"/></branch>
<attribute name="name" value="Malaria"/></branch>
</tree>

I am reading an XML file using the code given below, but every time I read the XML and print the same, the opening tag of XML is always missing, which in turn generates an error.

code to read xml :

package com.vaannila.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.vaannila.FormBean.XmlRetrivalForm;

public class AppletRefeshAction  extends Action {
    String filepath = "C:/Users/ashutosh_k/idoc/docRuleTool/WebContent/data/Malaria.xml";
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        XmlRetrivalForm xrf = (XmlRetrivalForm)form;
        String dieasename =xrf.getDieseasename();
        System.out.println("ghhjhhjkh"+dieasename);
        /* this part of the code is from jsp */
        //FileReader fis = new FileReader(new File(filepath));
        FileInputStream fis = new FileInputStream(new File(filepath));
        byte bin[] = new byte[(int) new File(filepath).length()];
        while(fis.read()>0){
        fis.read(bin);
        }
        System.out.println("I am here after reading the xml part of it ");
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        response.getOutputStream().write(bin);
//      response.getWriter().write(bin);
        String ashu = new String(bin);
        String iam =ashu.trim();
        System.out.println("i am in the new action class now ");
        System.out.println(iam);
        fis.close();
        /* this part of the code jsp ends here */
        return null;
    }

}

The output xml generated :

?xml version="1.0" encoding="UTF-8" standalone="no"?><tree>
<declarations>
    <attributeDecl name="name" type="String"/>
</declarations>
<branch>
<branch>
<attribute name="name" value="Excess Stool"/>
<branch>
<branch>
<attribute name="name" value="Do you have this condition for more than a weeks time"/>
<branch>
<attribute name="name" value=""/></branch>
<branch>
<attribute name="name" value=""/></branch>
</branch>
<branch>
<attribute name="name" value="No"/></branch>
<attribute name="name" value="Do you have watery stool"/></branch>
<branch>
<attribute name="name" value="No"/></branch>
</branch>
<branch>
<branch>
<attribute name="name" value="Was your peak temperature greater than 104"/>
<branch>
<branch>
<attribute name="name" value="Do you have chills"/>
</branch>
<branch>
<attribute name="name" value="No"/></branch>
<attribute name="name" value="Do you have high fever for more than a weeks time "/></branch>
<branch>
<attribute name="name" value="No"/></branch>
</branch>
<branch>
<attribute name="name" value="No"/></branch>
<attribute name="name" value="High Fever"/></branch>
<branch>
<branch>
<attribute name="name" value="Do you have pain in the left part of the head "/>
<branch>
<branch>
<attribute name="name" value="Duration of the headache spans for more than a day "/>
</branch>
<branch>
<attribute name="name" value="No"/></branch>
<attribute name="name" value="Do you have headache more than 5 times a day "/></branch>
<branch>
<attribute name="name" value="No"/></branch>
</branch>
<branch>
<attribute name="name" value="No"/></branch>
<attribute name="name" value="Bodyache"/></branch>
<attribute name="name" value="Malaria"/></branch>
</tree>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神也荒唐 2024-12-07 14:27:16

为什么会这样?

    FileInputStream fis = new FileInputStream(new File(filepath));
    byte bin[] = new byte[(int) new File(filepath).length()];
    while(fis.read()>0){
    fis.read(bin);
    }

而不是这个来阅读文字?

BufferedReader reader = new BufferedReader(new FileReader(filepath));
String line = null;
StringBuilder builder = new StringBuilder();
while ( (line = reader.readLine()) != null)
    builder.append(line);
reader.close();

Why this?

    FileInputStream fis = new FileInputStream(new File(filepath));
    byte bin[] = new byte[(int) new File(filepath).length()];
    while(fis.read()>0){
    fis.read(bin);
    }

instead of this to read the text?

BufferedReader reader = new BufferedReader(new FileReader(filepath));
String line = null;
StringBuilder builder = new StringBuilder();
while ( (line = reader.readLine()) != null)
    builder.append(line);
reader.close();
淤浪 2024-12-07 14:27:16

首先,您在每次循环迭代中以相同的偏移量读入字节缓冲区——您不能指望总是一次性读取整个文件。其次,不要在字节流和字符流之间进行不必要的转换——您应该将 XML 作为字节读取,并将其作为字节“转发”。请小心如何在字节数组和字符串之间进行转换 - 请记住 new String(byte[]) 使用平台默认字符编码(可能不是 utf-8)从字节转换为字符。

// read the file
ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
InputStream in = new BufferedInputStream(new FileInputStream(filepath));
int c;
while ((c = in.read()) != -1)
    out.write(c);
in.close();

// debug as string
if (debug) {
   System.out.writeln(new String(out.toBytes(), Charset.forName("utf-8"));
}


// forward to client through response
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
response.getOutputStream().write(out.toBytes());

First, you are reading into the byte buffer at the same offset in every loop iteration--you cannot expect to always read the entire file in one go. Second, don't unnecessarily convert between byte streams and character streams--you should read the XML as bytes and "forward" it as bytes. Be careful how you convert between byte arrays and strings--remember that new String(byte[]) uses the platform default character encoding (which may not be utf-8) to convert from bytes to characters.

// read the file
ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
InputStream in = new BufferedInputStream(new FileInputStream(filepath));
int c;
while ((c = in.read()) != -1)
    out.write(c);
in.close();

// debug as string
if (debug) {
   System.out.writeln(new String(out.toBytes(), Charset.forName("utf-8"));
}


// forward to client through response
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
response.getOutputStream().write(out.toBytes());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文