刚学android,遇到个读取sd卡xml的问题没解决,请教下大神们~
我想把sd卡上的一个xml读取并显示到TextView上,方法如下:
private void xmlPullParseXML(){
String path = Environment.getExternalStorageDirectory()+"/text.xml";
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(Thread.currentThread().getContextClassLoader().getResourceAsStream(path), "UTF-8");
int eventType = xmlPullParser.getEventType();
try {
while (eventType != XmlPullParser.END_DOCUMENT) {
String nodeName = xmlPullParser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if ("name".equals(nodeName)) {
res += "姓名: " + xmlPullParser.nextText() + " ";
} else if ("age".equals(nodeName)) {
res += "年龄: " + xmlPullParser.nextText() + "\n";
}
break;
}
eventType = xmlPullParser.next();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}
mTextView.setText(res);
}
为什么获取不到text.xml?不知道哪里的问题。。
------解决方案--------------------
看看路径是否正确,注意文件名的大小写是否错误了,在 android 上,文件名的大小写是敏感的
------解决方案--------------------
- Java code
File myfile=new File(path); if(myfile.exists()) { hasFile=1; } FileInputStream fileIS = new FileInputStream(path); StringBuffer sb=new StringBuffer(); BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS)); String readString = new String(); //just reading each line and pass it on the debugger while((readString = buf.readLine())!= null){ sb.append(readString); }
------解决方案--------------------
读取SD卡的权限加了么