简体   繁体   English

如何从Gradle传递文件路径到Java类?

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

So what I would like to do is run my Java Application using Gradle but also pass an .csv & .xml filepaths to my main class in order to use them in my bufferedReader & I have no idea how it should be done. 因此,我想做的是使用Gradle运行Java应用程序,还要将.csv和.xml文件路径传递给我的主类,以便在我的bufferedReader中使用它们,我也不知道应该怎么做。 My application is not build to jar, it's supposed to be run with gradle run task. 我的应用程序不是基于jar构建的,它应该与gradle run任务一起运行。 I want the user to be able to specify their own xml and csv file to use( in the command line) and then run the Java app, not being asked about paths to the files inside the app. 我希望用户能够指定要使用的xml和csv文件(在命令行中),然后运行Java应用程序,而不会被问到应用程序内文件的路径。 So for example let's take this line of code: Reader reader = Files.newBufferedReader(Paths.get("Here is the place I want gradle to include the path to csv")); 因此,例如,让我们采用以下代码行: 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

To @lance-java's comment of course there are other ways to accomplish the same task. @ lance-java的评论当然还有其他方法可以完成相同的任务。 He alluded to another the JavaExec task you can extend. 他提到了另一个可以扩展的JavaExec任务。 Here is an example of that if you wish to use that path. 如果您想使用该路径,请参见以下示例。

// 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