Create xml file and save it in internal storage android

前端 未结 3 1227
刺人心
刺人心 2020-12-04 18:19

I want to check in the android internal storage if new.xml exists(which will be created by me) then it should return me a handle for it and i may be easily able

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 19:17

    It's rather simple. This will help you:

    String filename = "file.txt";
    
    FileOutputStream fos;
    fos = openFileOutput(filename,Context.MODE_APPEND);
    
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(fos, "UTF-8");
    serializer.startDocument(null, Boolean.valueOf(true));
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    
    serializer.startTag(null, "root");
    
    for(int j = 0; j < 3; j++)
    {
        serializer.startTag(null, "record");
        serializer.text(data);
        serializer.endTag(null, "record");
    }
    
    serializer.endDocument();
    serializer.flush();
    
    fos.close();
    

    To read back data using DOM parser:

    FileInputStream fis = null;
    InputStreamReader isr = null;
    
    fis = context.openFileInput(filename);
    isr = new InputStreamReader(fis);
    
    char[] inputBuffer = new char[fis.available()];
    isr.read(inputBuffer);
    
    data = new String(inputBuffer);
    
    isr.close();
    fis.close();
    
    /*
    * Converting the String data to XML format so
    * that the DOM parser understands it as an XML input.
    */
    
    InputStream is = new ByteArrayInputStream(data.getBytes("UTF-8"));
    ArrayList xmlDataList = new ArrayList();
    
    XmlData xmlDataObj;
    DocumentBuilderFactory dbf;
    DocumentBuilder db;
    NodeList items = null;
    Document dom;
    
    dbf = DocumentBuilderFactory.newInstance();
    db = dbf.newDocumentBuilder();
    dom = db.parse(is);
    
    // Normalize the document
    dom.getDocumentElement().normalize();
    
    items = dom.getElementsByTagName("record");
    ArrayList arr = new ArrayList();
    
    for (int i = 0; i < items.getLength(); i++)
    {
        Node item = items.item(i);
        arr.add(item.getNodeValue());
    }
    

提交回复
热议问题