如何获取WEB-INF/class文件夹下的资源路径(java ee web动态项目)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18156991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:52:34  来源:igfitidea点击:

How can I get path of resource under WEB-INF/class folder (java ee web dynamic project)

javaservlets

提问by anna

I develop web dynamic project in Eclipse. One file, file named 'users.txt' is located under classes folder (WEB-INF/classes/users.txt).

我在 Eclipse 中开发 Web 动态项目。一个名为“users.txt”的文件位于 classes 文件夹 (WEB-INF/classes/users.txt) 下。

How I can get relative path of this file in class (base class, not servlet class)? I will use that path for append several lines of text.

如何在类(基类,而不是 servlet 类)中获取此文件的相对路径?我将使用该路径附加几行文本。

Christian this is the code that works for reading. Problem is I don't know how to create object for writing (output) in the same file with relative path.

Christian 这是适用于阅读的代码。问题是我不知道如何使用相对路径在同一文件中创建用于写入(输出)的对象。

public Products(){
    try{
        InputStream in = getClass().getClassLoader().getResourceAsStream("products.txt");    
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        readProducts(br);
        in.close();
            br.close();


    }catch(Exception e){
        System.out.println("File doesn't exists");
    }
    }

    public void readProducts(BufferedReader in) throws NumberFormatException, IOException{

        String id="";
        String name="";
        double price=0;

        StringTokenizer st;
        String line;

        while((line=in.readLine())!=null){
            st=new StringTokenizer(line,";");
            while(st.hasMoreTokens()){
                id=st.nextToken();
                name=st.nextToken();
                price=Double.parseDouble(st.nextToken());           
            }           
            products.put(id,new Product(id,name,price));
        }
    }

回答by Eugene Loy

Generally speaking you should not rely on modifying files in your web application directory.

一般来说,您不应该依赖修改 Web 应用程序目录中的文件。

One of the reasons is that servlet container is not obligated to extract your .warfile to the fs, it could, in theory, run your web application from memory. Yeah, Tomcat and most of the containers do unpack .warbut there is nothing in Java EE specs that says that they must do this.

原因之一是 servlet 容器没有义务将您的.war文件提取到 fs,理论上它可以从内存中运行您的 Web 应用程序。是的,Tomcat 和大多数容器都可以解包,.war但是 Java EE 规范中没有任何内容表明他们必须这样做。

Anyway, if you think that this worth the risk you can use ServletContext.getRealPathto get location of the file inside your webapp directory.

无论如何,如果您认为这值得冒险,您可以使用ServletContext.getRealPath来获取 webapp 目录中文件的位置。

This should look something like this:

这应该是这样的:

  1. Create a file myfileunder your webapp root (should be located in the same folderas WEB-INFin your .war).
  2. do something like this in your servlet (or anywhere where you can access servlet context):

    String filePath = getServletContext().getRealPath("myfile");

  1. 创建一个文件,myfile你的Web应用程序根目录下(应位于同一文件夹WEB-INF.war)。
  2. 在您的 servlet(或您可以访问 servlet 上下文的任何地方)中执行以下操作:

    String filePath = getServletContext().getRealPath("myfile");

Note that in order for this to work you should be able to fetch the file with request, like: http://<host>:<port>/<contextPath>/myfile(see method docs for details)

请注意,为了使其工作,您应该能够通过请求获取文件,例如:(http://<host>:<port>/<contextPath>/myfile有关详细信息,请参阅方法文档)