I'm using Gradle 7.0 and I made my project using the task Gradle Init. Then I imported it in Eclipse (2021-03 with buildship 3.1.5). Everything is fine but when I try to read or when I create a file in a java method with "/myfile.yaml" as path, it creates it (or try to read it) in the D:\ root folder (the partition where my eclipse is installed).
If I don't use the slash ("myfile.yaml" instead of "/myfile.yaml") the file is created in the root folder of the project. I thought it was supposed to be in src/main/resources until it's not built.
My goal is not really to create a file, it was just easier to test. My goal is to read some Yaml configuration files. What should I do to make sure the file will be in the build package and read in the correct place in both context (eclipse debbugging and the build package directory) ? And also, what is the best practice to set the path of the file (sonarlint alerts me about the way I do it : hardcoded in the method below, I know it's not supposed to be like this... I would use a constant but sonarlint doesn't like either).
The tree of the app :
- Project
- app
- src/main/java (containing java classes)
- src/main/resources (supposing to contain resources, yaml in my case)
- My build.gradle file
- yaml file when I try "myfile.yaml" without any /
- gradle/wrapper/gradle-wrapper.jar & gradle-wrapper.properies
- gradlew & gradlew.bat
- settings.gradle
My settings.gradle :
rootProject.name = 'myapp'
include('app')
My build.gradle:
plugins {
// Apply the application plugin to add support for building a CLI application in Java.
id 'application'
}
apply plugin:'java'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
implementation 'com.google.guava:guava:30.0-jre'
// Yaml reader
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.12.3'
testImplementation 'junit:junit:4.13.1'
}
//I tried with and without this sourceSets and the result was the same
sourceSets {
main {
java {
srcDirs= ["src/main/java"]
}
resources {
srcDirs= ["src/main/resources"]
}
}
}
application {
// Define the main class for the application.
mainClass = 'myapp.launchers.App'
}
And here is the method which writes a file using the Jackson library (yaml) :
public static void writeConfiguration() throws JsonGenerationException, JsonMappingException, IOException {
WorkerConfig wc = new WorkerConfig();
WorkerPathConfig wpc = new WorkerPathConfig();
wpc.setTmpdir("\\some\\uri\\file");
wpc.setOutputdir("\\some\\other\\uri\\file");
wc.setPathConfig(wpc);
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
objectMapper.writeValue(new File("/application.yaml"), wc);
}