Suppress Findbugs Warning in Static Initializer

Suppress Findbugs Warning in Static Initializer

I have a static initializer where I am creating a new File object. When I pass in the name to it FindBugs reports a warning due to the hard-coded absolute path. How can I suppress this warning?

private static final String fileName = "/tmp/m123.txt";
static {
    if (new File(fileName).exists()) {
        ....
    }
}
2

3 Answers

You could move this hard-coded filename to a properties file, or command line argument etc.

See this page for a tutorial on property files

In you want to ignore this warning though as per the page you can use -exclude filterFile.xml

5

You can use ENUM, I use ENUM to eliminate hardcoding of the strings/text both findbugs and pmd doesn't to show errors or warning.

public enum MyFiles {

    FILE_NAME("/kp/kp1/kp2.tx");

    private String value;

    MyFiles(String value){

        this.value = value;

    }

Your fileName is not uppercase, hence pmd would show error of type 1 for the same. So change it to upper case

private static final String FILE_NAME = "/tmp/m123.txt"

Normally I wouldn't advocate refactoring code too much to avoid warnings, but in this case you're stuck because you cannot annotate static initializers. You can move the code to a static method in another class which you may annotate with SuppressFBWarnings.

public class MainClass {
    private static final String FILE_NAME = "/tmp/m123.txt";

    static {
        HelperClass.loadFile(FILE_NAME);
    }
}

public class HelperClass {
    @SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME")
    public static void loadFile(String fileName) {
        if (new File(fileName).exists()) {
            ....
        }
    }
}

Extracting the code may actually be enough to avoid the warning, but I've never encountered this warning before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.