1

Given the following project setup, running ./gradlew run prints out Hello World correctly by reading in a resource file, but ./gradlew installDist && ./build/install/appresourcetest/bin/appresourcetest does not, as it cannot find the resource file. Why is that, and how can I fix this issue while keep using the installDist task?

As the resource is inside the jar, this probably has something to do with installDist's wrapper scripts' classpath setup, but that's where my understanding ends.

/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();

    }
}
5-to-9
  • 649
  • 8
  • 16

1 Answers1

2

As explained in this answer, you should not try to read the test.txt as a File, but ask for an InputStream to the ClassLoader using getResourceAsStream method. You should rewrite your method getFile, to somethin like:

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();

}

And also change String content = getFile("test.txt"); to String content = getFile("/test.txt");

M.Ricciuti
  • 11,070
  • 2
  • 34
  • 54