DCo*_*der 3 java file-io iostream decode decoding
我已经将图像编码到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();
Run Code Online (Sandbox Code Playgroud)
当我的xml包含多个图像时问题更严重.
使用StringBuilder而不是String s1.字符串连接s1=s1+ (char)inst.read();是问题所在.
要修复的另一件事 - 使用BufferedInputStream因为从字节读取FileInputStream是非常低效的.
使用可用是个坏主意,这样更好
for(int i; (i = inst.read()) != -1;) {
...
}
Run Code Online (Sandbox Code Playgroud)
总而言之
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();
Run Code Online (Sandbox Code Playgroud)
如果文件小到足以适应内存那么
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");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
787 次 |
| 最近记录: |