从servlet读取资源文件 [英] Reading a resource file from a servlet

查看:157
本文介绍了从servlet读取资源文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从servlet中读取文本文件,该文件是使用Jersey制作的,并使用Gradle构建的.服务器是Tomcat 9.

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

我的文件结构:

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

我的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"
}

Tomcat提取WAR后,file.txt与源软件包位于同一目录中.

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

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

我试图使用类加载器加载文件,但是类路径似乎是Tomcat的bin目录.我也不想对路径进行硬编码.
在这里加载文件的最佳方法是什么?

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?

推荐答案

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

这篇关于从servlet读取资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆