Android项目中访问assets文件夹的方法是什么?
我访问放置在项目文件夹(例如“资产”)中的 XML 文件,以打开文件并从文件中读取数据。
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
InputStream iS = this.getAssets().open("myFile.xml");
Document doc = docBuilder.parse(iS);
但是如果我想编辑该文件,我找不到保存它的路径。
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
OutputStream f0;
byte buf[] = xmlString.getBytes();
**f0 = new FileOutputStream("/assets/wines.xml");**
//f0 = new FileOutputStream("file:///assets/wines.xml");
for(int i=0;i<buf .length;i++) {
f0.write(buf[i]);
}
f0.close();
buf = null;
我总是在以下行获得 FileNotFoundException
:
f0 = new FileOutputStream("/assets/wines.xml");
有什么想法吗?谢谢!
I access to an XML file placed in a project folder (for instance 'assets') for open and read data from file.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
InputStream iS = this.getAssets().open("myFile.xml");
Document doc = docBuilder.parse(iS);
but If I want to edit the file, I can't find the path to save it.
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
OutputStream f0;
byte buf[] = xmlString.getBytes();
**f0 = new FileOutputStream("/assets/wines.xml");**
//f0 = new FileOutputStream("file:///assets/wines.xml");
for(int i=0;i<buf .length;i++) {
f0.write(buf[i]);
}
f0.close();
buf = null;
I obtain always a FileNotFoundException
at line:
f0 = new FileOutputStream("/assets/wines.xml");
Any ideas? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您尝试
编辑或写入
文件到资产或原始文件夹
。我想这是不可能的。 这是不可能的If you are trying to
edit or write
file toassets or raw folder
. I guess it is not possible. It cannot be doneBettery 尝试将其保存到 SD 卡或内部存储
使用
File sdDir = [Environment.getExternalStorageDirectory()][1];
获取 sdcard 路径。并且不要忘记给予许可
Bettery try saving it to sd card or internal storage
Use
File sdDir = [Environment.getExternalStorageDirectory()][1];
to get the sdcard path.And don't forget to give permission