刚学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?不知道哪里的问题。。

解决方案 »

  1.   

    先通过path 判断file是否存在
    File.exists()
    存在再去读取。
      

  2.   

    看看路径是否正确,注意文件名的大小写是否错误了,在 android 上,文件名的大小写是敏感的
      

  3.   

     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);          }可以参考http://hi.baidu.com/maguowei/blog/item/2a757f091af4e8bc2fddd414.html/cmtid/1244bd8f47ca7ce1f11f362d