簡體   English   中英

如何從Gradle傳遞文件路徑到Java類?

[英]How to pass a filepath from Gradle to Java class?

因此,我想做的是使用Gradle運行Java應用程序,還要將.csv和.xml文件路徑傳遞給我的主類,以便在我的bufferedReader中使用它們,我也不知道應該怎么做。 我的應用程序不是基於jar構建的,它應該與gradle run任務一起運行。 我希望用戶能夠指定要使用的xml和csv文件(在命令行中),然后運行Java應用程序,而不會被問到應用程序內文件的路徑。 因此,例如,讓我們采用以下代碼行: Reader reader = Files.newBufferedReader(Paths.get(“這是我希望gradle包含csv路徑的地方”));

// sample gradle task to execute a java jar
task runFromGradle() {
    print("java -jar myJar.jar path/to/some.csv".execute().text)
}

// some sample class with a main that accepts args. first arg is the csv path
class Scratch {
    public static void main(String[] args) {
        String csvPath = args[0];
        Reader reader = Files.newBufferedReader(Paths.get(csvPath));
        // do whatever with reader...
    }
}

# from command line
$ gradle runFromGradle

@ lance-java的評論當然還有其他方法可以完成相同的任務。 他提到了另一個可以擴展的JavaExec任務。 如果您想使用該路徑,請參見以下示例。

// note the `JavaExec` task is only available from the java plugin,
// this may or may not what your app needs
// reference: https://docs.gradle.org/current/javadoc/org/gradle/api/tasks/JavaExec.html
apply plugin: 'java'

task runFromGradle(type: JavaExec) {
  // here gradle has access to the raw sourcesets
  // so we can directly use them for the runtime
  classpath = sourceSets.main.runtimeClasspath

  main = 'com.me.Main'

  // arguments to pass to the application
  args 'path/to/some.csv'
}

# from command line
$ gradle runFromGradle

# java class is the same

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM