我尝试在return语句之前放一个toast,但String变量返回一个空字符串。
public String getXmlFile(String pathFile,Context context){
String xmlFileString = "";
AssetManager am = context.getAssets();
try {
InputStream str = am.open(pathFile);
int length = str.available();
byte[] data = new byte[length];
xmlFileString = new String(data);
} catch (IOException e1) {
e1.printStackTrace();
}
return xmlFileString;
}
答案 0 :(得分:1)
使用此功能阅读byte[]
中的InputStream
:
public byte[] convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString().getBytes("UTF-8");
}
答案 1 :(得分:1)
使用它来读取XML。如果不将UTF-8传递给InputStreamReader,您可能会得到一个损坏的XML字符串。
BufferedReader reader = new BufferedReader(new InputStreamReader(
context.getAssets().open(pathFile), HTTP.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
现在,在我的情况下将字符串解析为XML时,还存在每个换行符被解释为自己的XML节点的问题。空间也是一个问题。在上面读取的字符串上使用它来修复:
String oneLineXml = sb.toString().replace("\n", "").replaceAll("> +<", "><");
只有这样你才能解析字符串,如下所示:
Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new ByteArrayInputStream(
oneLineXml.getBytes(HTTP.UTF_8))));