2

This code creates the file, but it's always empty.

I have seen some examples using a StringWriter, but my XML files can become so large, it doesn't seem practical saving it to a writer, converting it to a string, and then writing it to a file. It should be a stream.

Or perhaps I don't know what I'm talking about and have totally confused myself.

private void createXMLfile(File file, long folderRoot) throws IllegalArgumentException, IllegalStateException, IOException {
    // https://developer.android.com/reference/org/xmlpull/v1/XmlSerializer
    // https://stackoverflow.com/questions/5181294/how-to-create-xml-file-in-android
    file.createNewFile();
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(fileOutputStream, G.KML.XML_ENCODING); // XML_ENCODING = "UTF-8"
    serializer.startDocument(G.KML.XML_ENCODING, Boolean.valueOf(true));
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    serializer.startTag(null, G.KML.KML); // KML = "kml"
    serializer.endTag(null, G.KML.KML);
    serializer.endDocument();
    serializer.flush();
    fileOutputStream.flush();
    fileOutputStream.close();
}

My Manifest permissions:

<!-- Following two permissions are for import/export functionality -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This file is being written to:

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

...but the user can change where the file gets saved.

qkzoo1978
  • 315
  • 3
  • 11
  • 1
    @elyor Flushing is unnecessary, but won't cause a problem. `createNewFile` will only create a new file if one doesn't already exist, and since we don't know the provenance of the passed-in file, also seems harmless. – Dave Newton Jan 02 '19 at 21:17

1 Answers1

0

setFeature should be called first or not, createNewFile is not needed. close already does a flush.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • "startDocument... This method can only be called just after setOutput." I take that to mean before anything else? per: https://developer.android.com/reference/org/xmlpull/v1/XmlSerializer.html#startDocument(java.lang.String,%20java.lang.Boolean) – qkzoo1978 Jan 02 '19 at 21:56
  • `setFeature` looks wrong: telling to use XML pull parsing/generation, after startDocument was issued. I would have expected an IllegalStateException however. As createFile already created an empty file, that would explain the resulting situation. – Joop Eggen Jan 03 '19 at 10:20