2012-07-05 66 views
0

的确定大小我有一个简单的代码,从给定的URL中获取XML文件:的Java - XML文档

DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(link); 

代码返回XML文档(org.w3c.dom.Document中)。我只需要获取生成的xml文档的大小。有没有优雅的方式来做到这一点,而不涉及第三方罐子?

P.S.大小(KB),或MB,而不是数量点头

+0

size in form kb?或节点的数量? – 2012-07-05 11:52:57

+0

KB。我编辑了我的文章 – guest86 2012-07-05 11:54:02

回答

2

第一原始版本:将文件加载到本地缓冲区。然后你知道你的输入有多长时间。然后从缓冲区中解析XML:

URL url = new URL("..."); 
InputStream in = new BufferedInputStream(url.openStream()); 
ByteArrayOutputStream buffer1 = new ByteArrayOutputStream(); 
int c = 0; 
while((c = in.read()) >= 0) { 
    buffer1.write(c); 
} 

System.out.println(String.format("Length in Bytes: %d", 
    buffer1.toByteArray().length)); 

ByteArrayInputStream buffer2 = new ByteArrayInputStream(buffer1.toByteArray()); 

Document doc = DocumentBuilderFactory.newInstance() 
    .newDocumentBuilder().parse(buffer2); 

缺点是RAM中的附加缓冲区。

第二个更优雅版:总结与定制java.io.FilterInputStream计数通过它流字节输入流:

URL url = new URL("..."); 
CountInputStream in = new CountInputStream(url.openStream()); 
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in); 
System.out.println(String.format("Bytes: %d", in.getCount())); 

这里是CountInputStream。所有read()方法都被覆盖以委托给超类并计算所得字节数:

public class CountInputStream extends FilterInputStream { 

    private long count = 0L; 

    public CountInputStream(InputStream in) { 
    super(in); 
    } 

    public int read() throws IOException { 
    final int c = super.read(); 
    if(c >= 0) { 
     count++; 
    } 
    return c; 
    } 

    public int read(byte[] b, int off, int len) throws IOException { 
    final int bytesRead = super.read(b, off, len); 
    if(bytesRead > 0) { 
     count += bytesRead; 
    } 
    return bytesRead; 
    } 

    public int read(byte[] b) throws IOException { 
    final int bytesRead = super.read(b); 
    if(bytesRead > 0) { 
     count += bytesRead; 
    } 
    return bytesRead; 
    } 

    public long getCount() { 
    return count; 
    } 
} 
0

的也许这:

document.getTextContent().getBytes().length; 
+0

不,getTextContent返回null,尽管文档被填充:\ – guest86 2012-07-05 12:06:37

+0

不优雅的方式:创建文件.xml和file.length() – Phebus40 2012-07-05 12:11:56

0

你可以这样说:

long start = Runtime.getRuntime().freeMemory(); 

构建你的XML文档对象。然后再次调用上述方法。

Document ocument = parser.getDocument(); 

long now = Runtime.getRuntime().freeMemory(); 

System.out.println(" size of Document "+(now - start)); 
+0

这不会工作 - 会有很多对象(如DOM节点)分配内存,而不仅仅是包含文档内容的字符串。 – 2012-07-05 15:43:00

0

将XML文件解析到DOM树后,源文档(作为字符串)不再存在。您只需从该文档构建一个节点树 - 因此不再可能从DOM文档准确确定源文档的大小。

你可以transform the DOM document back into an XML file using the identity transform;但这是一种非常全面的获取大小的方法,它仍然不能完全匹配源文档的大小。

对于您要做的事情,最好的方法是自己下载文档,记下大小,然后使用InputStream将它传递给DocumentBuilder.parse方法。