I am trying to read. a config from my resources folder in Java project from my deployed code. I am able to read from my local laptop but after deployment as JAR .manifest file, it says path does not exist.
So my Java maven project str: src/main/java/..
and config path as follows:
Java code to read this config where file.exists()
always returns false.
Trial 1: When config path is : src/main/resources/config.yaml
.
File configPath = new File(Objects.requireNonNull(getClass().getClassLoader().getResource("config.yaml")).getFile());
if (!configPath.exists()) {
Log("ERROR", "Config file does not exist "); // this is printed
}
Trial 2: When config path is src/main/resources/feed/configs/config.yaml
.
File dir = new File(Objects.requireNonNull(getClass().getClassLoader().getResource("feed/configs")).getFile());
if (!dir.exists()) {
Log("ERROR", "Config folder does not exist, "ERROR"); // THIS IS PRINTED
return;
}
File[] configFiles = configPath.listFiles(); // NOT EXECUTED AS ABOVE IS RETURNED
CodePudding user response:
Since you have added the maven tag, I am assuming you are using maven.
As the .yaml is inside the resources folder you should be using getResourceAsStream()
/src/main/resources/config.yaml:
first: value1
second: value2
To read the file and its content:
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;
public class Example {
InputStream inputStream = null;
final Properties properties = new Properties();
public Example() {
try {
inputStream =
this.getClass().getClassLoader().getResourceAsStream("config.yaml");
properties.load(inputStream);
} catch (IOException exception) {
LOG("ERROR", "Config file does not exist ");
} finally {
if (inputStream != null){
try {
inputStream.close();
} catch (Exception e) {
LOG("ERROR", "Failed to close input stream");
}
}
}
}
public printValues(){
LOG("INFO", "First value is: " properties.getProperty("first"));
}
}