从Android Asset文件夹中读取xml文件

mar*_*f73 8 xml android android-assets

我正在尝试从assets文件夹中读取相同的文件" xmlfile.xml ",并从SD卡sdcard/download /中读取另一个副本.

我可以从SD卡读取:

  • 正确的回归真实
  • Esite Return True

我无法从Assets文件夹中读取:

  • 不正确的返回错误
  • Esite返回错误

这段代码不适用

        File source = new File("file:///android_asset/xmlfile.xml");
        boolean unfile = source.isFile();
        boolean Esiste = source.exists();

        try
        {
          // todo
        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

这段代码工作

        File source = new File("/sdcard/" + "download" + "/" + "xmlfile.xml");
        boolean unfile = source.isFile();
        boolean Esiste = source.exists();

        try
        {
          // todo
        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

有人可以解释我如何从Assets文件夹中读取文件.

谢谢马克

Raw*_*ode 12

要打开资产,您需要以下代码:

InputStream is = getAssets().open("xmlfile.xml")
Run Code Online (Sandbox Code Playgroud)


小智 7

使用此功能

// Converting given XML file name to String form
String mOutputText = getxml("yourxml.xml");

/**
 * Function used to fetch an XML file from assets folder
 * @param fileName - XML file name to convert it to String
 * @return - return XML in String form
 */
private String getXml(String fileName) {
    String xmlString = null;
    AssetManager am = context.getAssets();
    try {
        InputStream is = am.open(fileName);
        int length = is.available();
        byte[] data = new byte[length];
        is.read(data);
        xmlString = new String(data);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return xmlString;
}
Run Code Online (Sandbox Code Playgroud)