簡體   English   中英

如何在我的 WebContent 文件夾中獲取文件的真實路徑?

[英]How can I get real path for file in my WebContent folder?

我需要在我的 WebContent 目錄中獲取文件的真實路徑,以便我使用的框架可以訪問該文件。 它只需要字符串文件作為屬性,所以我需要在 WebContent 目錄中獲取該文件的真實路徑。

我使用 Spring Framework,因此應該可以在 Spring 中創建解決方案。

如果您需要在 servlet 中使用它,請使用getServletContext().getRealPath("/filepathInContext")

getServletContext().getRealPath("") - 如果內容從 .war 存檔中可用,這種方式將不起作用。 getServletContext() 將為空。

在這種情況下,我們可以使用另一種方式來獲取真實路徑。 這是獲取屬性文件 C:/Program Files/Tomcat 6/webapps/myapp/WEB-INF/classes/somefile.properties 路徑的示例:

// URL returned "/C:/Program%20Files/Tomcat%206.0/webapps/myapp/WEB-INF/classes/"
URL r = this.getClass().getResource("/");

// path decoded "/C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
String decoded = URLDecoder.decode(r.getFile(), "UTF-8");

if (decoded.startsWith("/")) {
    // path "C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
    decoded = decoded.replaceFirst("/", "");
}
File f = new File(decoded, "somefile.properties");

您必須告訴 java 將路徑從您的 pc 更改為您的 java 項目,因此如果您使用 spring,請使用:

@Autowired
ServletContext c;

String UPLOAD_FOLDEdR=c.getRealPath("/images"); 

但是如果你使用 servlets 就使用

String UPLOAD_FOLDEdR = ServletContext.getRealPath("/images");  

所以路徑將是/webapp/images/ :)

這種方法使用資源加載器獲取應用程序中文件的絕對路徑,然后向上移動幾個文件夾到應用程序的根文件夾。 不需要 servlet 上下文! 如果您的 WEB-INF 文件夾中有“web.xml”,這應該可以工作。 請注意,您可能需要考慮僅將其用於開發,因為這種類型的配置通常最好從應用程序外部存儲。

public String getAppPath()
{
    java.net.URL r = this.getClass().getClassLoader().getResource("web.xml");
    String filePath = r.getFile();
    String result = new File(new File(new File(filePath).getParent()).getParent()).getParent();

    if (! filePath.contains("WEB-INF"))
    {
        // Assume we need to add the "WebContent" folder if using Jetty.
        result = FilenameUtils.concat(result, "WebContent");
    }

    return result;
}

在這種情況下,我傾向於將我需要的內容提取為資源 (MyClass.getClass().getResourceAsStream()),將其作為文件寫入臨時位置,然后將此文件用於其他調用。

這樣我就不必理會僅包含在 jar 中或位於某處的內容,具體取決於我當前使用的 Web 容器。

將請求作為參數包含在內。 Spring 會在調用映射方法時傳遞請求對象

@RequestMapping .....
public String myMethod(HttpServletRequest request) {
   String realPath = request.getRealPath("/somefile.txt");
   ...

您可以使用 Spring Resource 接口(尤其是 ServletContextResource): http : //static.springsource.org/spring/docs/current/javadoc-api/org/springframework/core/io/Resource.html

我的解決方案是:..../webapps/mydir/ (..../webapps/ROOT/../mydir/)

String dir = request.getSession().getServletContext().getRealPath("/")+"/../mydir";
            Files.createDirectories(Paths.get(dir));

當您也想在開發和生產級別使用 arff.txt 時,請嘗試使用它

  String path=getServletContext().getRealPath("/WEB-INF/files/arff.txt");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM