Windows中如何用Gradle构建kotlin项目build jar包,并执行kotlin jar
一,如何用Interllij IDEA 来构建基于Gradle的kotlin项目?
- 首先,打开Interllij IDEA, 选择File-->New-->Project, 在“New project” 窗口左侧选择Gradle,右侧选择kotlin,如下图所示:
- 点击Next按钮填写项目相关信息,项目名为example1(可自定义), 如下图所示:
- 接着一直点击“Next”按钮即可创建完成,创建完成后的项目如下图所示:
二,如何用Gradle 构建kotlin项目的jar包?
- 第一步:新建一个简单的kotlin程序HelloWorld
- Go to 项目名[example1]-->src-->main-->kotlin, 右键单击菜单选择“New-->Package”, 输入包名[自定义],如下图所示:
- 点击OK, 包com.my.stuff创建成功,
- 创建kotlin file: 右键单击包名,选择new --> kotlin file
- 写最简单的HelloWorld.kt程序并运行,如下图所示
第二步:配置Gradle构建生成jar包
- 修改工程名example1下的gradle配置文件build.gradle如下
buildscript { ext.kotlin_version = '1.1.4-3' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: 'kotlin' apply plugin: 'application' mainClassName = 'com.my.stuff.HelloWorldKt' ======>修改为你所创建的程序 jar { manifest { attributes 'Main-Class': 'com.my.stuff.HelloWorldKt' ======>修改为你所创建的程序 } // This line of code recursively collects and copies all of a project's files // and adds them to the JAR itself. One can extend this task, to skip certain // files or particular types at will from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } } defaultTasks 'run' repositories { mavenCentral() } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" testCompile 'junit:junit:4.11' testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version" } task wrapper(type: Wrapper) { gradleVersion = "4.1" }
- 开始构建:打开cmd, 进入项目所在的路径,运行命令 > gradlew.bat build,如下图所示:
- build成功后,查看生成的jar包。Go to 项目名[example1]-->build-->libs, 生成的example1.jar显示在此,如下图所示:
三、运行jar
- 打开cmd, 进入jar所在的目录[example1/build/libs/example1.jar]。运行:> java -jar example1.jar