我正在尝试从 assets 文件夹中读取相同的文件“xmlfile.xml”,并从 SD 卡 sdcard/download/ 中读取另一个副本。
我可以从 SD 卡读取:
我不能不从资产文件夹中读取:
此代码无法工作
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();
}
此代码可以工作
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();
}
有人可以解释我如何从 Assets 文件夹中读取文件。
谢谢 马可
要打开资产,您需要以下代码:
InputStream is = getAssets().open("xmlfile.xml")
使用此功能
// 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;
}
这一定会对你有帮助。 要读取文件形式的资产文件夹,您需要一个
InputStream
对象。
语法:
InputStream yourobj=getApplicationContext().getAssets().open("Path to xml file");
所以实时代码可以是:
InputStream in_s = getApplicationContext().getAssets().open("www/application/app/client/controllers/data1.xml");
这里
data1.xml
是路径内的文件。
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();
}
我发现执行以下操作更容易:
val xmlStream = context.resources.getXml(R.xml.example)
我相信这是 XmlPullParser 的子集,但它已经足够好了。
如果您只想获取 .xml 中特定项目的值,您可以使用以下方法:
object AssetUtils {
fun readXmlItemByName(
context: Context,
assetFileName: String,
itemName: String
): String? {
try {
// Open file stream from project asset folder
val fileInputStream = context.assets.open(assetFileName)
// Create buffer to stream file into
val size = fileInputStream.available()
val buffer = ByteArray(size)
// Read stream into buffer
fileInputStream.read(buffer)
fileInputStream.close()
// Write buffer to string
val utf8: Charset = Charset.forName("UTF-8")
val string = String(buffer, utf8)
// Check lines for xml item name
val xmlItemName = "\"" + itemName + "\""
val lines = string.lines()
lines.forEach {
// Found parameterName in line
if (it.contains(xmlItemName)) {
// Extract value
val value = it.substringAfter(">").substringBefore("</")
// Return value
if (value.isNotBlank()) {
return value
}
}
}
return null
} catch (e: Exception) {
Log.e("AssetsUtils", "readXmlParameter(): ${e.message}")
return null
}
}
}