最近做一个项目,打算把所有的配置写在一个文件里,方便软件的管理和使用。
我的配置文件是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文件夹,然后将你的文件拷入该文件夹下,如下如所示:
读取代码的方法如下:
InputStream is = getResources().openRawResource(R.raw.configuration);
这个问题整整纠缠了我两天!!特此总结一下,希望可以帮助遇到同样问题的朋友~
下面介绍一下从asset中获取文件并读取数据的方法(该资源文件只能读,不能写)
asset目录下,称为原生文件,这类文件在被打包成apk文件时是不会进行压缩的,android使用AssetManager对asset文件进行访问,通过getResources().getAssets()获得AssetManager其内有一个open()方法可以根据用户提供的文件名,返回一个InputStream对象供用户使用。代码如下:
getResources().getAssets().open(fileName);