Beginner servlet question: accessing files in a .war, which path?

This question already has an answer here:

  • Recommended way to save uploaded files in a servlet application 2 answers

  • You should never rely on relative paths in file IO while reading a resource. The working directory is namely dependent on the way how the application is started. You have total no control over this. Always use absolute paths in file IO.

    The normal approaches are:

  • Put the resource in the classpath or add its path to the classpath. Then you can obtain it by the classloader as follows:

    String classPathLocation = "filename.ext";
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream(classPathLocation);
    // ...
    

    Note the way how the classloader and the resource is obtained. You should not obtain it from the current class like as getClass().getResourceAsStream() . In a WAR there is namely possibly means of multiple classloaders. The classloader of the current class might not know about the desired resource per se, the context one will.

  • Put the resource in webcontent (there where the WEB-INF folder is and all other public web resources). Then you can obtain its absolute path as follows which you can just continue to use in the usual file IO code:

    String relativeWebPath = "/filename.ext";
    String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
    InputStream input = new FileInputStream(absoluteDiskPath);
    // ...
    

    Note that this only works when the WAR is expanded, else it will just return null .


  • I owe this answer to BalusC, but since I didn't really understand it at first, I simplified it:

    The working directory (the starting point for relative paths) depends on the way the application is started, so you don't really have control over this. Luckily there's a way to get the absolute path of anything in your web application's root directory, which is as follows:

    getServletContext().getRealPath("pathToAnyFileInYourWebAppDocumentRoot.ext")
    

    (This gives a String)

    That's all you have to do. Unfortunately this only works when your app is deployed as a directory, not as a .war file (where it will return null ).

    (See BalusC's answer for another way, and where this answer came from).

    链接地址: http://www.djcxy.com/p/55884.html

    上一篇: 如何将Play应用部署到Websphere 7

    下一篇: 初学者servlet问题:访问.war中的文件,哪个路径?