sidebar 隐藏/显示

one method

            String filename = "test/testfiles/testDAOUpload.xml";
            File testfile = new File(filename);
            System.out.println(testfile.getAbsolutePath());
            FileInputStream fileinput = new FileInputStream(testfile
                    .getAbsolutePath());
            int x = fileinput.available();
            byte b[] = new byte[x];
            fileinput.read(b);
            String xmlDocument = new String(b);
            System.out.println(xmlDocument);

想把如XML格式的String转化成InputStream来生成一个Document

本想使用new StringBufferInputStream(string); 

Java API提示StringBufferInputStream已经deprecated,但可以使用StringReader class来生成stream,问题是我也看过StringReader的API,并没有提供和InputStream有关的方法。

难道这是一个BUG?

这里好像也有人提出过同样的问题。 http://bugs.sun.com/bugdatabase/view_bug.do;:YfiG?bug_id=4094886

 

最后只好用ByteArrayInputStream方法

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();

ByteArrayInputStream stream = new
ByteArrayInputStream(string.getBytes());
Document doc = docBuilder.parse(stream);
stream.close();
话说sun就不打算解决这种小的bug么?
当然,生成一个Document也可以使用InputSource类
Document document = docBuilder.parse(new InputSource(new StringReader(content)));
先生成一个StringReader,然后再构件一个InputSource,一样也可达成目的。 
共1页 1