gpt4 book ai didi

java - 无法加载保存在代码外部的属性文件

转载 作者:行者123 更新时间:2023-12-01 15:41:36 25 4
gpt4 key购买 nike

import static com.crawler.constants.CrawlerConstants;
import static com.crawler.constants.CrawlerConstants.CRAWLER4J;


import java.util.Properties;


public final class Configurations {

private static Properties prop = new Properties();


public static String getStringProperty(String key, String defaultValue) {
if (prop == null || prop.getProperty(key) == null) {
return defaultValue;
}
return prop.getProperty(key);
}

public static int getIntProperty(String key, int defaultValue) {
if (prop == null || prop.getProperty(key) == null) {
return defaultValue;
}
return Integer.parseInt(prop.getProperty(key));
}

public static short getShortProperty(String key, short defaultValue) {
if (prop == null || prop.getProperty(key) == null) {
return defaultValue;
}
return Short.parseShort(prop.getProperty(key));
}

public static long getLongProperty(String key, long defaultValue) {
if (prop == null || prop.getProperty(key) == null) {
return defaultValue;
}
return Long.parseLong(prop.getProperty(key));
}

public static boolean getBooleanProperty(String key, boolean defaultValue) {
if (prop == null || prop.getProperty(key) == null) {
return defaultValue;
}
return prop.getProperty(key).toLowerCase().trim().equals("true");
}

static {
try {
prop.load(Configurations.class.getClassLoader()
.getResourceAsStream(CONFIG_DIR + "/" + CRAWLER4J));
} catch (Exception e) {
prop = null;
System.err.println("WARNING: Could not find crawler4j.properties file in class path. I will use the default values.");
}
}
}

在我上面的 try 循环中,它没有加载crawler4j.properties 文件。和之前一样-

try {
prop.load(Configurations.class.getClassLoader()
.getResourceAsStream("crawler4j.properties"));
}

因此它能够直接从 src/main/resources 文件夹加载它。但我想加载保存在不同目录中的代码之外的这个crawler4j.properties 文件。所以我已经将crawler4j.properties文件存储在/my/dir/crawler4j.properties中,这是我想要修改的try循环-

try {
prop.load(Configurations.class.getClassLoader()
.getResourceAsStream(CONFIG_DIR + "/" + CRAWLER4J_PROP));
}

CONFIG_DIR 包含\my\dir 并且 CRAWLER4J 具有crawler4j.properties,但不知何故它没有加载并且它将捕获异常 block 。任何建议为什么会发生。

最佳答案

如果您尝试将某些内容作为资源加载,它必须位于类路径上——这就是资源的定义(给予或获取)。

要从文件系统路径加载它,请使用 load(InputStream) (或加载(Reader))。

关于java - 无法加载保存在代码外部的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7958305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com