3

I am using Haxe and OpenFL and I got a program that generates a Xml file.

However, I can't figure out how to save that file. I can create Xml tree and check it's valid, but for my life I can't figure out how to write the file.

So, in simple, how to do I write(and create) a file in Haxe? I want to be able to save my newly created Xml File (they serve as sort of settings file and initialization files for my program) on computer, so that I can load it later?

Mark Knol
  • 9,663
  • 3
  • 29
  • 44
Mandemon
  • 372
  • 3
  • 22

1 Answers1

3

Found the solution right after writing this question.

Solution is to first to use sys.io.File.write() to create the file, then File.saveContent() to save the data in. You can get string from Xml with toString function, the ultimate solution looks like this:

    if (!FileSystem.exists("maps"))
    {
        FileSystem.createDirectory("maps");
    }
    var number:Int = 1;
    if (FileSystem.exists("maps/" + filename + ".xml"))
    {
        while(FileSystem.exists("maps/" + filename + number +".xml"))
        {
            number++;
        }

        filename = filename + number;
    }


    File.write("maps/" + filename + ".xml", false);
    File.saveContent("maps/" + filename + ".xml", root.toString());

This checks if the directory exist and if not, create it and if the file exist, create a new numbered file rather than override it (for the moment, still working on the save feature)

This solution only works on c++, haven't tested others much yet but Flash does not work

Mandemon
  • 372
  • 3
  • 22
  • 1
    Do you need `File.write`? I think `File.save content()` should be sufficient. And this should work on all "sys" platforms: cpp, neko, php. I'm surprised C# and Java don't support these standard classes yet. Also I believe there are implementations for Air and NodeJS if that interests you. If so let me know and I'll find the links... – Jason O'Neil Aug 11 '13 at 22:38
  • I found that File.write() creates the file, while File.saveContent() saves the data into the file. So, if you want to create a new file, rather than write into existing file, you need to use File.write() to create it. – Mandemon Aug 12 '13 at 14:09
  • Using `File.write()` is in this case incorrect. `File.saveContent()` writes data to a new file or, if that file already exists, replaces all its content (see [implementation](https://github.com/HaxeFoundation/haxe/blob/1c79168a33163acb82ed6d26ab59dc8d11768287/std/cpp/_std/sys/io/File.hx#L37)). Using `File.write()` here is a no-op or maybe even an error, if you're leaving behind that open file descriptor. Finally, the reason why you haven't been able to run this on Flash is that the `sys.*` APIs are only available to the so called "sys" targets (Neko, Java, C++ ...). – Jonas Malaco Feb 06 '16 at 15:19