【发布时间】:2012-10-06 07:19:33
【问题描述】:
我需要在 android 中将 xml 文件作为字符串加载,以便将其加载到 TBXML xml 解析器库并解析它。即使对于一些 KB 的非常小的 xml 文件,我现在必须以字符串形式读取文件的实现需要大约 2 秒。是否有任何已知的快速方法可以在 Java/Android 中将文件作为字符串读取?
这是我现在的代码:
public static String readFileAsString(String filePath) {
String result = "";
File file = new File(filePath);
if ( file.exists() ) {
//byte[] buffer = new byte[(int) new File(filePath).length()];
FileInputStream fis = null;
try {
//f = new BufferedInputStream(new FileInputStream(filePath));
//f.read(buffer);
fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
Log.d("TourGuide", e.toString());
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ignored) {
}
}
//result = new String(buffer);
}
return result;
}
【问题讨论】:
-
取决于您当前读取文件的方式。发布您的代码,以便有人可以帮助您。
-
我现在没有代码。我稍后会发布它。但在此之前欢迎任何建议:)
-
Panos,我不知道您如何解析 XML 文件,但请尝试在每行添加一个 StringBuffer 对象,而不是添加到一个字符串。 StringBuffer 更快。
-
请检查我正在使用的代码和建议。我看到我在那里有字符串连接。我会改变的。还有其他建议吗?
标签: android string optimization