Create xml file and save it in internal storage android

前端 未结 3 1220
刺人心
刺人心 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:16

    Use openFileOutput to create file in internal storage and getFileStreamPath for checking if they already exists and working with them

    To read data into array just open file stream and use any appropriate XML parser

    0 讨论(0)
  • 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<XmlData> xmlDataList = new ArrayList<XmlData>();
    
    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<String> arr = new ArrayList<String>();
    
    for (int i = 0; i < items.getLength(); i++)
    {
        Node item = items.item(i);
        arr.add(item.getNodeValue());
    }
    
    0 讨论(0)
  • 2020-12-04 19:18

    Use getFilesDir() to get the path to where you can create files. Check if the file exists by creating a file object File newXml = new File(getFilesDir+"/new.xml"). Then check if it exists using if(newXml.exists()).

    To parse the data, refer dev docs . As you can see in the XmlPullParser example, it can return a list.

    0 讨论(0)
提交回复
热议问题