#2878 Creating a File in Fantom

johndoe Mon 31 Oct 2022

Hello everyone,

So, I've been experimenting with Fantom a bit, but I cannot find a way to create a text file using Fantom. By this, I mean that I cannot find a way to write a line of code (or a couple of lines) to create a file. I found the "createFile" but do not fully understand how to use it.

I did something like this below:

nameofFile := "Test.txt" File.createFile(nameofFile)

I figure I am doing something ridiculous, but I haven't noticed it yet. Also, how do I place strings within such a file? I have a C++ background so I am used to just using ofstream.

Henry Mon 31 Oct 2022

Hi johndoe!

In Fantom, the createFile function is there to just create the actual file on the system at the specified directory, for example:

`C:/Somefolder/`.toFile.createFile("something.txt")

Will create a file named something.txt in the directory under C:/Somefolder/ This is a convenience method for using create at that same position

`C:/Somefolder/something.txt`.toFile.create

This line will achieve the same results.

As for writing data to a file, this can be done using the open method. This method "opens" the file for reading & writing (by default, if you wish to open it only for reads you can pass "r" as the mode: open("r").

This function returns a Buf object type, which has several available methods for writing data to. Bufs can be complicated but are extremely powerful for dealing with files as well as general memory storage.

After writing data to said Buf, you then just need to then close the the Buf (Though I don't believe this is technically required)

For Example:

sampleText := "Lorem ipsum dolor sit amet"
file := `C:/foo/bar.txt`.toFile.open.writeChars(sampleText).close

That code snippet will create a file named "bar.txt" at C:/foo/ if it didn't exist already, and will write the sample text to said file.

Writing files becomes more complex as you start to mess around with files that already exist, etc but hopefully that should help you out!

brian Mon 31 Oct 2022

If you just want to stream some data, maybe using sys::File.out is easier than open (although both will work):

/work/src> fansh
Fantom Shell v1.0.78.3105 ('?' for help)
fansh> `foo.txt`.toFile.out.print("some data").close
true
fansh> quit

/work/src> cat foo.txt
some data

Also take a look at the examples

Login or Signup to reply.