如何获取位于SD卡上的xml文件并阅读内容? Android的

时间:2013-02-22 10:08:59

标签: android xml string get sd-card

我遇到了问题,我需要从我的sdcard目录中读取一个xml文件并至少保存内容,然后选择xml标签之间的de值,但是如果你可以帮我读取和转换为字符串它已经非常有用了。

文件目录: Environment.getExternalStorageDirectory()+“/ SCity /”+ now now currentmillis 文件名: Notes.xml

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:-2)

将您的文件放在资产文件夹中:

public class Main extends Activity {

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btn = (Button) findViewById(R.id.button1);

    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Load XML for parsing
            AssetManager assetManager = getAssets();
            InputStream inputStream = null;
            try {
                inputStream = assetManager.open("test.xml");
            } catch (IOException e) {

            }

            String s = readTextFile(inputStream);
            TextView tv = (TextView)findViewById(R.id.textView1);
            tv.setText(s);
        }
    });
}

private String readTextFile(InputStream inputStream) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    byte buf[] = new byte[1024];
    int len;
    try {
        while ((len = inputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
        inputStream.close();
    } catch (IOException e) {

    }
    return outputStream.toString();
  }
}