获取文件的所在路径(windows和linux都适用)
- 使用类路径资源方式(已测试-推荐):
// 将 javaSettings.cfg 放在 src/main/resources/config 目录下
String configPath = IatCapacity.class.getResource("/config/javaSettings.cfg").getPath();
getParam(configPath);
- 使用相对路径:
// 相对于项目根目录
String configPath = new File("src/main/java/com/iflytek/spark/knowledge/controller/iat/javaSettings.cfg").getAbsolutePath();
getParam(configPath);
- 通过系统属性传递:
在 pom.xml 中:
<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><configuration><systemPropertyVariables><config.path>${project.basedir}/src/main/java/com/iflytek/spark/knowledge/controller/iat/javaSettings.cfg</config.path></systemPropertyVariables></configuration></plugin></plugins>
</build>
在 Java 代码中:
String configPath = System.getProperty("config.path");
getParam(configPath);
- 最佳实践方案:
public class IatCapacity {private static final Logger logger = LoggerFactory.getLogger(IatCapacity.class);private static final String CONFIG_FILE = "/config/javaSettings.cfg";public IatCapacity() {try {// 从资源目录加载配置URL configUrl = IatCapacity.class.getResource(CONFIG_FILE);if (configUrl == null) {throw new IllegalStateException("Configuration file not found: " + CONFIG_FILE);}String configPath = configUrl.getPath();logger.info("Loading configuration from: {}", configPath);getParam(configPath);} catch (Exception e) {logger.error("Failed to initialize IatCapacity", e);throw new RuntimeException("Failed to initialize IatCapacity", e);}}
}
项目结构建议:
knowledge-web/└── src/└── main/├── java/│ └── com/│ └── iflytek/│ └── spark/│ └── knowledge/│ └── controller/│ └── iat/│ └── IatCapacity.java└── resources/└── config/└── javaSettings.cfg
这样的好处是:
- 配置文件集中管理在 resources 目录
- 使用类路径加载,不依赖具体文件系统路径
- 打包后依然可以正常工作
- 适用于不同的运行环境
如果你想保持配置文件在当前位置,也可以使用相对路径:
public class IatCapacity {private static final String CONFIG_FILE = "javaSettings.cfg";public IatCapacity() {try {// 获取当前类的目录路径String classPath = IatCapacity.class.getProtectionDomain().getCodeSource().getLocation().getPath();String configPath = new File(new File(classPath).getParentFile(), CONFIG_FILE).getPath();logger.info("Loading configuration from: {}", configPath);getParam(configPath);} catch (Exception e) {logger.error("Failed to initialize IatCapacity", e);throw new RuntimeException("Failed to initialize IatCapacity", e);}}
}