从XML文件中读取花费很长时间(Reading from XML file taking very long time)

编程入门 行业动态 更新时间:2024-10-21 11:38:27
从XML文件中读取花费很长时间(Reading from XML file taking very long time)

我已经将图像编码到xml文件中,并且在解码时我遇到了很长的执行时间问题(对于中等大小的图像,差不多20分钟),下面的代码显示了我现在如何将xml转换为xml需要很长时间的字符串有很大的图像,他们的任何其他方式来获得xml字符串在较少的时间。

String s1= new String(); System.out.println("Reading From XML file:"); InputStream inst = new FileInputStream("c:/collection.xml"); long size = inst.available(); for(long i=0;i<size;i++) { s1=s1+ (char)inst.read(); } inst.close();

当我的xml包含多个图像时问题更糟糕。

I have encoded images into xml file and at the time of decoding I am experiencing problem of long execution time(almost 20 mins for moderate size image), Following code shows how I am now converting xml into string which is taking very long time for xml having large images, Is their any other way around to get xml into string in less time.

String s1= new String(); System.out.println("Reading From XML file:"); InputStream inst = new FileInputStream("c:/collection.xml"); long size = inst.available(); for(long i=0;i<size;i++) { s1=s1+ (char)inst.read(); } inst.close();

Problem is worse when my xml contain multiple images.

最满意答案

使用StringBuilder而不是String s1。 字符串连接s1=s1+ (char)inst.read(); 是问题。

另一个需要解决的问题是使用BufferedInputStream因为从FileInputStream读取字节的效率非常低。

使用可用是个坏主意,这样更好

for(int i; (i = inst.read()) != -1;) { ... }

总而言之

StringBuilder sb= new StringBuilder(); try (InputStream inst = new BufferedInputStream(new FileInputStream("c:/collection.xml"))) { for(int i; (i = inst.read()) != -1;) { sb.append((char)i); } } String s = sb.toString();

如果文件足够小以适应内存的话

File file = new File("c:/collection.xml"); byte[] buf = new byte[(int)file.length()]; try (InputStream in = new FileInputStream(file)) { in.read(buf); } String s = new String(buf, "ISO-8859-1");

Use StringBuilder instead of String s1. String concatenation s1=s1+ (char)inst.read(); is the problem.

Another thing to fix - use BufferedInputStream because reading by byte from FileInputStream is extremely inefficient.

It is bad idea to use available, this is better

for(int i; (i = inst.read()) != -1;) { ... }

all in all

StringBuilder sb= new StringBuilder(); try (InputStream inst = new BufferedInputStream(new FileInputStream("c:/collection.xml"))) { for(int i; (i = inst.read()) != -1;) { sb.append((char)i); } } String s = sb.toString();

and if file is small enough to fit into memory then

File file = new File("c:/collection.xml"); byte[] buf = new byte[(int)file.length()]; try (InputStream in = new FileInputStream(file)) { in.read(buf); } String s = new String(buf, "ISO-8859-1");

更多推荐

本文发布于:2023-08-01 02:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1353976.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:很长时间   文件   XML   Reading   time

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!