Reading from XML file taking very long time
decode, decoding, file-io, iostream, java
Solution
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");
Problem
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.