如何通过Gradle将多文件源码导出为单个源码文件?
Hey there! Totally get where you're coming from—using an IDE for development is way more comfortable, but coding-game platforms usually want a single file. Lucky for you, Gradle makes this super straightforward with a custom task. Let me walk you through how to set it up:
Step 1: Add a Custom Task to Your Build File
Depending on whether you use Groovy (build.gradle) or Kotlin DSL (build.gradle.kts), pick the corresponding code snippet below and add it to your project's build file.
Groovy Version (build.gradle)
task concatenateSources(type: Copy) { // Point to your main source directory (adjust if your sources are elsewhere) from 'src/main/java' // Include all Java files (swap *.java to *.kt for Kotlin, *.py for Python, etc.) include '**/*.java' // Define where the combined file will go into 'build/generated/sources' // Name your output file whatever you like rename { 'combined-code.java' } // Optional: Add comments to track which original file each section comes from eachFile { file -> filter { line -> if (file.name == file.sourceName) { "// Original file: ${file.relativePath}\n" + line } else { line } } } // Make sure the output folder exists before running doFirst { mkdir destinationDir } }
Kotlin DSL Version (build.gradle.kts)
tasks.register<Copy>("concatenateSources") { from("src/main/java") include("**/*.java") into("build/generated/sources") rename { "combined-code.java" } eachFile { filter { line -> if (name == sourceName) { "// Original file: ${relativePath}\n$line" } else { line } } } doFirst { mkdir(destinationDir) } }
Step 2: Customize the Task for Your Project
Tweak these parts to match your setup:
- Source Directory: Update
src/main/javaif your code lives in a different folder (likesrc/main/kotlin). - File Extension: Change
*.javato match your programming language (e.g.,*.ktfor Kotlin,*.cppfor C++). - Output Name: Swap
combined-code.javato a name that makes sense for your project. - Remove Headers: If you don't need the original file path comments, delete the entire
eachFileblock.
Step 3: Run the Task
Execute the task from your terminal:
- On macOS/Linux:
./gradlew concatenateSources - On Windows:
gradlew.bat concatenateSources
Your combined source file will be waiting in build/generated/sources/combined-code.java (or your custom path/name). Just copy its content and paste it into your coding-game platform!
Bonus: Handling Dependencies (If Needed)
If your code uses external libraries that aren't available on the coding-game platform, you might need to bundle those dependencies into your combined file. For advanced cases, you can pair this task with the Shadow Plugin to shade dependencies, but most coding-game platforms support standard libraries out of the box, so this is usually unnecessary.
内容的提问来源于stack exchange,提问作者Valentin Michalak

