Android读取文件方法总结

首先,说一句android真是坑爹啊!不过细想想,是我看书太少吧。。。
最近做一个项目,打算把所有的配置写在一个文件里,方便软件的管理和使用。
我的配置文件是XML格式的,当文件写好之后,使用DOM对XML文件进行了解析,代码如下:

public void initServer(){
try {
DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
DocumentBuilder dombuilder = domfac.newDocumentBuilder();

InputStream is = new FileInputStream("./configuration.xml");
Document doc = dombuilder.parse(is);
Element root = doc.getDocumentElement();
NodeList configuration = root.getChildNodes();
if(configuration != null){
for(int i = 0 ; i < configuration.getLength() ; i ++){
Node conf = configuration.item(i);
for(Node node = conf.getFirstChild(); node != null; node = node.getNextSibling()){
if(conf.getNodeType() == Node.ELEMENT_NODE){
if(conf.getNodeName().equals("ip")){
ip = conf.getFirstChild().getNodeValue();
}
if(conf.getNodeName().equals("port")){
port = new Integer(conf.getFirstChild().getNodeValue());
}
if(conf.getNodeName().equals("map-key")){
mykey = conf.getFirstChild().getNodeValue();
}
}
}
}
}

} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

程序编译出现文件读写错误的异常!!后来查了资料才知道,Android不支持读取与工程直接子级的文件,解决办法是:
在res文件夹下新建一个raw文件夹,然后将你的文件拷入该文件夹下,如下如所示:
[img]http://dl2.iteye.com/upload/attachment/0089/9805/5d614cad-da6e-344b-8885-77cb8848a23e.png[/img]
读取代码的方法如下:
InputStream is = getResources().openRawResource(R.raw.configuration);


这个问题整整纠缠了我两天!!特此总结一下,希望可以帮助遇到同样问题的朋友~
下面介绍一下从asset中获取文件并读取数据的方法(该资源文件只能读,不能写)
asset目录下,称为原生文件,这类文件在被打包成apk文件时是不会进行压缩的,android使用AssetManager对asset文件进行访问,通过getResources().getAssets()获得AssetManager其内有一个open()方法可以根据用户提供的文件名,返回一个InputStream对象供用户使用。代码如下:
getResources().getAssets().open(fileName);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值