You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Windows批处理文件运行IntelliJ的Kotlin项目并修复异常

问题:Kotlin脚本通过批处理运行时无输出且不创建文件

我有一个Kotlin脚本,通过println()输出日志信息并创建文件。在IntelliJ中运行该脚本时,能正常创建文件并在控制台显示输出;但通过批处理文件运行时,既看不到命令提示符中的输出,也不会创建文件。

Kotlin代码

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\\😈hi_there.txt", textToFile = "Hello there)")
    println("File created")
    println("Program is Finished)")
}

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

原批处理脚本

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

运行批处理后的输出

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>

问题原因

  1. 运行方式错误:直接用java命令运行Kotlin编译后的字节码会缺少Kotlin标准库依赖,导致程序无法正常启动执行,自然不会有输出和文件生成。
  2. 编译命令执行逻辑问题:kotlinc本身是Windows批处理文件,直接在脚本中调用时会新开独立窗口执行,执行完毕后直接退出,后续的java命令无法在正确的上下文环境中运行。

修复方案

要实现控制台输出和文件操作,修改批处理脚本如下:

  1. 使用call命令调用kotlinc,确保编译过程在当前命令窗口执行,完成后再执行后续步骤。
  2. 用kotlin命令替代java命令运行编译后的代码,kotlin命令会自动处理Kotlin标准库的依赖加载,保证程序正常执行。

可用的批处理脚本

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

内容的提问来源于stack exchange,提问作者Nikita Avramenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:52:53