2

I am developing a plugin using org.sonarsource.sonarqube:sonar-plugin-api:6.3. I am trying to access a file in my resource folder. The reading works fine in unit testing, but when it is deployed as a jar into sonarqube, it couldn't locate the file.

For example, I have the file Something.txt in src/main/resources. Then, I have the following code

private static final String FILENAME = "Something.txt";

String template = FileUtils.readFile(FILENAME);

where FileUtils.readFile would look like

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

This question is similar with reading a resource file from within a jar. I also have tried with /Something.txt and Something.txt, both does not work.If I put the file Something.txt in the classes folder in sonarqube installation folder, the code will work.

Community
  • 1
  • 1
Ggg
  • 249
  • 1
  • 7
  • 18
  • Please check that your file is correctly package din your plugin (open the final JAR and ensure the file is at the root). Then `/Something.txt` should work. – Julien H. - SonarSource Team Apr 04 '17 at 12:18
  • @JulienH.-SonarSourceTeam Yes, I checked. The file is already correctly included in the JAR. I opened the JAR, and the file is in the root folder. The code will always have `inputStream` as null if i use both `Something.txt` or `/Something.txt`. The `/`, is it operating system dependent? – Ggg Apr 05 '17 at 08:37
  • Is it different when using `getClass().getClassLoader()` compared to use `Thread.getCurrentThread().getClassLoader()`? – Ggg Apr 06 '17 at 03:41

1 Answers1

1

Try this:

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

Your should not use getContextClassLoader(). see Short answer: never use the context class loader!

Community
  • 1
  • 1
Arigion
  • 3,267
  • 31
  • 41