android从sdcard创建并读取xml

时间:2016-06-29 11:32:03

标签: android xml

我使用2按钮,第一个按钮在sdcard中创建xml文件
和第二个按钮来读取这个xml 这是我的代码:

String xml_root;
ListView lv_emp;
static final String KEY_NAME = "name";
static final String KEY_AGE = "age";
List<HashMap<String, String>> empHashmap;
List<ClassEmp> empList = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_empacc);

    xml_root = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "\n" +
            "<employees>" + "\n" +
            "\t" + "<emp>" + "\n" +
            "\t" +  "\t" + "<name>" + "jame" + "</name>" + "\n" +
            "\t" +  "\t" + "<age>" + "17" + "</age>" + "\n" +
            "\t" +  "</emp>" + "\n" +
            "\t" +  "<emp>" + "\n" +
            "\t" +  "\t" + "<name>" + "natalie" + "</name>" + "\n" +
            "\t" +  "\t" + "<age>" + "20" + "</age>" + "\n" +
            "\t" + "</emp>" + "\n" +
            "</employees>";

    Button bt_create2 = (Button)findViewById(R.id.bt_createfileT2);
    bt_create2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
                if (!newFolder.exists()) {
                    newFolder.mkdir();
                }

                File file = new File(newFolder, "Test" + ".xml");
                if (!file.exists()) {
                    file.createNewFile();
                    FileOutputStream fOut = new FileOutputStream(file);
                    OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
                    myOutWriter.append(xml_root);
                    myOutWriter.close();
                    fOut.close();
                }
            } catch (Exception e) {
                System.out.println("e: " + e);
            }
        }
    });

    Button bt_read2 = (Button)findViewById(R.id.bt_readfileT2);
    bt_read2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                lv_emp = (ListView)findViewById(R.id.lv_Emp);
                File file = new File(Environment.getExternalStorageDirectory() + "TestFolder/Test.xml");
                InputStream is = new FileInputStream(file.getPath());
                XmlPullParserEmp parser_Emp = new XmlPullParserEmp();
                empList = parser_Emp.parse(is);
                BinderDataEmp bd_Emp = new BinderDataEmp(Empacc.this, empHashmap);
                lv_emp.setAdapter(bd_Emp);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    });
}

使用此代码,在sdcard上的TestFolder中创建Test.xml 但我看不懂。
如何解决?

1 个答案:

答案 0 :(得分:0)

在阅读文件

期间,您很可能缺少/(斜杠)

使用此功能并重试:

File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.xml");