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