File IO Tutorial (Neko)

Introduction
This tutorial covers simple ascii and binary file input and output using the Haxe/neko libraries. The neko.io.File class provides a very simple yet powerful interface for working with files.

Ascii Files
In this example, we will create and write a few lines to an ascii file, then we will read what was written. Haxe provides two ways of reading ascii files. They can be opened and read a little at a time, or they can be read all at once. This example demonstrates both methods.

We are using neko.io.File, haxe.io.Output, and haxe.io.Input from the standard library. haxe.io.Output and haxe.io.Input are the parent classes of neko.io.FileOutput and neko.io.FileInput, respectively.

Note that both the File.read and File.write methods take two parameters: the filename and a boolean flag where true indicates that the file is a binary file.

While we read the file line by line, the Input and Output classes also allow the file to be written or read by the character, byte or value for any basic type. When reading a file using the FileInput class, you must surround the read statement in a try catch block as was done in the example since there is no way of detecting an EOF. The FileInput.eof method seems like it might do this, but it doesn't.

Compile and run with:

The output should be:

The file "ascii_file.txt" should now exist in the current directory. It contains the same two lines.

Binary Files
In this example, we will create and write some data to a binary file, then we will read what was written. We are writing four values of different types: an int, a 32 bit int, a double, and a string.

Note that the length of the string must be known in order to read it. If it is not a fixed size string, it would be a good idea to store the string length in the file before the string.

Also note that there are no writeInt or readInt methods. We have to use the methods that specify the width of the int. Regular int's in neko are 31 bits, so the example has to convert neko int's for use with the writeInt32 and readInt32 methods.

Compile and run with:

The output should be:

The file "binary_file.dat" should now exist in the current directory. It contains the data in binary little endian format.