Search code examples
kotlinbatch-fileintellij-idea

How to run Kotlin IntelliJ Idea project from Windows bat file?


I have a Kotlin script that creates files and outputs some log messages using println(). When I run the script from IntelliJ, it works as expected, creating the files and showing the output in the console. However, when I run the script using a batch file, the files are not created, and I don't see any output in the command prompt.

Here is my Kotlin code:

import java.io.File

fun main(args: Array<String>) {
    println("Starting main function")
    println("Hello World!")
    createFile("C:\\0_Scripts\\CSV_ To proper format\\👽hi_there.txt", textToFile = "Hello there)")
    createFile("C:\\0_Scripts\\CSV_ To proper format\\11111.txt", textToFile = "Hello there)")
    createFile("C:\\0_Scripts\\CSV_ To proper format\\\uD83D\uDE08hi_there.txt", textToFile = "Hello there)")
    println("File created")
    println("Program is Finished)")
}

fun createFile(absolutePathToFileWithExtension: String, textToFile: String) =
    File(absolutePathToFileWithExtension).writeText(textToFile)

And here is the batch script I'm using to compile and run the Kotlin script:


cd C:\Users\user\IdeaProjects\TestScript
kotlinc src\main\kotlin\Main.kt -d bin
java -cp bin MainKt
pause



When I run the batch script, I see the following output, but there are no log messages or created files:

C:\0_Scripts\CSV_ To proper format>test.bat
src\main\kotlin\Main.kt:4:10: warning: parameter 'args' is never used
fun main(args: Array<String>) {
         ^

C:\Users\user\IdeaProjects\TestScript>

What could be causing this issue, and how can I fix it to:

.1. See the console output .2. Manipulate files when running the IntelliJ Project from the batch file?

Edit!

Thanks to the answers this is the working script:

cd C:\Users\user\IdeaProjects\TestScript
call kotlinc src\main\kotlin\Main.kt -d bin
kotlin -cp bin MainKt
pause

Solution

  • When you call kotlinc on the command line, you are running the file .../kotlinc/bin/kotlinc.bat. When you run a batch file from another batch file, the control is transferred to the new batch file and never returns to the calling batch file (i.e. it's more like a goto than a call). So, what is happening is that your batch file runs kotlinc and then nothing else happens, because kotlinc.bat doesn't return to your script, but instead returns to the command line.

    To fix this, you need to replace this line:

    kotlinc src\main\kotlin\Main.kt -d bin
    

    with:

    call kotlinc src\main\kotlin\Main.kt -d bin
    

    Also, you need to do what Fox2Code says in the other answer (run your application using call kotlin instead of java).