Reading a resource file from a servlet

2019-08-16 00:20发布

问题:

I want to read a text file from a servlet which is made using Jersey and built using Gradle. The server is Tomcat 9.

My file structure:

project
    + src
        + package
            + App.java
    + res
        + file.txt

My build.gradle:

apply plugin: "java"
apply plugin: "war"

project.webAppDirName = "WebContent"

sourceSets {
    main {
        java {
            srcDirs = ["src"]
        }
        resources {
            srcDirs = ["res"]
        }
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile "org.glassfish.jersey.containers:jersey-container-servlet:2.25.1"
}

war {
    archiveName "api.war"
}

After Tomcat extracts the WAR, file.txt is in the same directory as the source packages:

WEB-INF
    + classes
        + package
            + App.class
        + file.txt

I tried to load the file using the class loader but the classpath seems to be the bin directory of Tomcat. I also don't want to hardcode the path.
What is the best way to load the file here?

回答1:

InputStream in = package.App.class.getClassloader().getResourceAsStream("file.txt")