从 Android Asset 文件夹中读取 xml 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10550621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read xml file from Android Asset folder
提问by marcoqf73
I'm trying to read the same file "xmlfile.xml" from the assetsfolder and also another copy from the SD card sdcard/download/.
我正在尝试从资产文件夹中读取同一个文件“ xmlfile.xml”,并从 SD 卡sdcard/download/读取另一个副本。
I can Read from SD Card:
我可以从 SD 卡读取:
- unfile Return True
- Esite Return True
- 取消归档返回真
- Esite 返回真
I can't not Read from Assets folder:
我不能从 Assets 文件夹中读取:
- unfile Return False
- Esite Return False
- 取消归档 返回False
- Esite 返回False
This code il NOT Working
此代码不工作
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();
}
This code il Working
此代码 il 工作
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();
}
someone can explain me how can I read the file from the Assets folder.
有人可以解释我如何从 Assets 文件夹中读取文件。
thanks marco
谢谢马可
回答by Rawkode
To open an asset you'd need the following piece of code:
要打开资产,您需要以下代码:
InputStream is = getAssets().open("xmlfile.xml")
回答by Mufazzal
Use this function
使用这个功能
// 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;
}
回答by Ajay Pandya
try
{
AssetManager aManager = Class.getAssets();
InputStream iStream = aManager.open("file.xml");
int length = iStream.available();
byte[] data = new byte[length];
iStream.read(data);
assetString = new String(data).toString();
}
catch (IOException e)
{
e.printStackTrace();
}
回答by Anuj Sharma
This will surely help you.
For reading a file form assets folder you need a InputStreamObject.
这肯定会帮助你。要读取文件形式的资产文件夹,您需要一个InputStream对象。
Syntax:
句法:
InputStream yourobj=getApplicationContext().getAssets().open("Path to xml file");
So the live code can be:
所以实时代码可以是:
InputStream in_s = getApplicationContext().getAssets().open("www/application/app/client/controllers/data1.xml");
Here data1.xmlis the file inside the path.
这data1.xml是路径中的文件。

