Why cant I create and write a file?

Hello,
I want to generate files with source code in them. For that I do the following (an excerpt):

    fun generate_AST_nodes(grammar:List<String>, class_name:String) {
        var file_exists:Boolean = false
        if (File(directory_path + "/" + class_name + ".kt").exists())
            file_exists = true
        var class_file:File = File(directory_path + "/" + class_name + ".kt")
        class_file.createNewFile()
        if (!file_exists)
            class_file.writeText("abstract " + class_name + "{")
...

in my test cases the file is not written to. I also use

class_file.writeText("...")

without if clause.
Does anyone know why? Thanks!

I mean, put some console logging in, or use some break points. Something like this, for example:

if (!file_exists) {
    println("file does not already exist, writing code to file")
    class_file.writeText("abstract " + class_name + "{")
    ....
}

Then see if it ever prints that text.

1 Like

Why do you create two (supposedly) identical File objects? If you create one and then use it twice, then there’s no possibility of a typo in one causing your code to misbehave.

But yes, as Skater901 says, this is a matter of common-or-garden debugging, for which this forum isn’t a good place. As well as adding logging showing which code path it’s taking, I’d also log things like the values of variables like file_exists and class_file, so you can check their values are what you expect.

(Once it’s working, you can either remove the logs, or better still use a logging library and log at a low level such as DEBUG or TRACE, so you can keep the logging in the code, but not see the results until you need them again.)

Also, you can simplify:

var file_exists:Boolean = false
if (File(directory_path + "/" + class_name + ".kt").exists())
    file_exists = true

to

val fileExists = File(directory_path + "/" + class_name + ".kt").exists()

Or, better, if you reuse the File object, to:

val fileExists = classFile.exists()

(Note that camelCase, not snake_case, is standard for Kotlin identifiers.)

1 Like