JAR的target/classes文件夹中不存在文件,该文件是从resources项目文件夹中读取的



我正在努力阅读。从我部署的代码中的Java项目中的resources文件夹中的配置。我可以从本地笔记本电脑上读取,但在部署为JAR.manifest文件后,它表示路径不存在。

因此,我的Java maven项目str:src/main/java/..和配置路径如下:

读取此配置的Java代码,其中file.exists()总是返回false。

试用1:当配置路径为: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
}

试用版2:当配置路径为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

由于您添加了maven标记,我假设您使用的是maven。

由于.yaml在resources文件夹中,您应该使用getResourceAsStream()

/src/main/resources/config.yaml:

first: value1
second: value2

要读取文件及其内容:

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