没有资源文件的Gradle installDist

时间:2018-11-12 09:04:25

标签: java gradle build.gradle

给出以下项目设置,运行./gradlew run可以通过读入资源文件正确打印出Hello World,但是./gradlew installDist && ./build/install/appresourcetest/bin/appresourcetest不能,因为找不到资源文件。为什么会这样?在继续使用installDist任务的同时如何解决此问题?

由于资源位于jar中,这可能与installDist的包装脚本的类路径设置有关,但这就是我的理解要结束的地方。

/build.gradle:

plugins {
    id 'java'
    id 'application'
}

group 'com.example.application'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

mainClassName = "demo.Main"

repositories {
    mavenCentral()
}

dependencies {

}

/settings.gradle:

rootProject.name = 'appresourcetest'

/src/main/resources/test.txt

Hello World

/src/main/java/demo/Main.java

package demo;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        //should not fail:
        String content = getFile("test.txt");
        System.out.println(content);
    }


    //code taken from:
    //https://www.mkyong.com/java/java-read-a-file-from-resources-folder/
    private static String getFile(String fileName) {

        StringBuilder result = new StringBuilder("");

        //Get file from resources folder
        ClassLoader classLoader = Main.class.getClassLoader();
        File file = new File( classLoader.getResource( fileName).getFile());

        try (Scanner scanner = new Scanner( file)) {

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                result.append(line).append("\n");
            }

            scanner.close();

        } catch ( IOException e) {
            e.printStackTrace();
        }

        return result.toString();

    }
}

1 个答案:

答案 0 :(得分:2)

this answer中所述,您不应尝试将test.txt读为File,而应使用InputStream向类加载器要求getResourceAsStream方法。您应该将方法getFile重写为类似以下内容:

private static String getFile(String fileName) {
    StringBuilder result = new StringBuilder("");
    try (InputStream in = Main.class.getResourceAsStream(fileName); Scanner scanner = new Scanner(in)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            result.append(line).append("\n");
        }
    } catch (IOException e) {
        // handle exception here
    }
    return result.toString();

}

然后将String content = getFile("test.txt");更改为String content = getFile("/test.txt");