从SonarQube插件内部读取资源文件



我正在使用org.sonarsource.sonarqube:sonar-plugin-api:6.3开发一个插件。我正在尝试访问resource文件夹中的文件。读取在单元测试中工作正常,但是当它作为jar部署到sonarqube中时,它找不到该文件。

例如,我在 src/main/resourcesSomething.txt了文件。然后,我有以下代码

private static final String FILENAME = "Something.txt";
String template = FileUtils.readFile(FILENAME);

其中FileUtils.readFile看起来像

public String readFile(String filePath) {
    try {
        return readAsStream(filePath);
    } catch (IOException ioException) {
        LOGGER.error("Error reading file {}, {}", filePath, ioException.getMessage());
        return null;
    }
}
private String readAsStream(String filePath) throws IOException {
    try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
        if (inputStream == null) {
            throw new IOException(filePath + " is not found");
        } else {
            return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        }
    }
}

此问题类似于从 jar 中读取资源文件。我也尝试过/Something.txtSomething.txt,两者都不起作用。如果我将文件Something.txt放在 sonarqube 安装文件夹中的 classes 文件夹中,代码将起作用。

试试这个:

File file = new File(getClass().getResource("/Something.txt").toURI());
BufferredReader reader = new BufferedReader(new FileReader(file));
String something = IOUtils.toString(reader);

你不应该使用 getContextClassLoader((。 请参阅简短的回答:永远不要使用上下文类加载器!

最新更新