代码之家  ›  专栏  ›  技术社区  ›  Eugeniu Torica

如何在Struts 2应用程序中读取文本文件[duplicate]

  •  7
  • Eugeniu Torica  · 技术社区  · 16 年前

    当我遇到servlets的类似问题时,我使用这个.getContextPath()(或类似的东西)返回Web服务器中文件夹的绝对路径。

    编辑: 谢谢你们的回答。对我来说:

    String path=GetPointsOfInterestAction.class.getResource("../../../resources/visitor_attractions.txt")
    

    4 回复  |  直到 10 年前
        1
  •  10
  •   BalusC    16 年前

    如果它位于webapp的类路径中,则只需使用:

    InputStream input = servletContext.getResourceAsStream("file.txt");
    

    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt");
    

    如果将其放置在webcontent中,则只需使用:

    InputStream input = new FileInputStream(servletContext.getRealPath("file.txt"));
    

    path/to/file.txt . 你可以得到 ServletContext 在Struts by ServletActionContext#getServletContext()

    编辑: 您使用以下内容编辑了您的问题:

    编辑:谢谢你们的回答。对我来说:

    String path=GetPointsOfInterestAction.class.getResource("../../../resources/visitor_attractions.txt")
    

    这实际上不是“正确”的方法,但这也是可行的。你只需要确保你 知道 相对的 与文件的实际路径相反的文件路径 GetPointsOfInterestAction 班级。这个类当然放在另一个包中,所以您基本上需要返回一个目录(就像您在普通磁盘文件系统中所做的那样: cd ../ 等等)。同样,这不是最优雅的方式。您需要使用前面提到的两种方法之一,即资源名称 resources/visitor_attractions.txt .

        2
  •  3
  •   Bozho    16 年前

    Here

    ServletActionContext.getServletContext()

    你似乎知道该怎么做了。

        3
  •  3
  •   Poindexter    16 年前

    Resource Bundle . 我使用它们来查找属性文件。我相信目录只需要位于类路径上,ResourceBundle就会找到它。

        4
  •  2
  •   Pascal Thivent    16 年前

    如果文件位于类路径上(不清楚,但这是个好主意),我建议使用实用程序类 org.apache.struts2.util.ClassLoaderUtils . 从其java文档中:

    此类对于以容错方式加载资源和类非常有用,这种方式可以跨不同的应用程序服务器工作。

    特别注意 ClassLoaderUtils.getResourceAsStream(String resourceName, Class callingClass) getRessource() :

    此方法将尝试加载 资源,请使用以下方法 (按顺序):

    • Thread.currentThread().getContextClassLoader()
    • 从…起 ClassLoaderUtil.class.getClassLoader()
    • 从 callingClass.getClassLoader()
    推荐文章