我已经将图像编码到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");更多推荐
发布评论