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

前端 未结 9 988
既然无缘
既然无缘 2020-12-16 02:33

I need to get real path for file in my WebContent directory, so that framework that I use can access that file. It only takes String file as attribute, so I need to get the

相关标签:
9条回答
  • 2020-12-16 02:58

    you must tell java to change the path from your pc into your java project so if you use spring use :

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

    but if you use servlets just use

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

    so the path will be /webapp/images/ :)

    0 讨论(0)
  • 2020-12-16 03:01

    my solve for: ..../webapps/mydir/ (..../webapps/ROOT/../mydir/)

    String dir = request.getSession().getServletContext().getRealPath("/")+"/../mydir";
                Files.createDirectories(Paths.get(dir));
    
    0 讨论(0)
  • 2020-12-16 03:02

    You could use the Spring Resource interface (and especially the ServletContextResource): http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/core/io/Resource.html

    0 讨论(0)
  • 2020-12-16 03:06

    getServletContext().getRealPath("") - This way will not work if content is being made available from a .war archive. getServletContext() will be null.

    In this case we can use another way to get real path. This is example of getting a path to a properties file 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");
    
    0 讨论(0)
  • 2020-12-16 03:06

    In situations like these I tend to extract the content I need as a resource (MyClass.getClass().getResourceAsStream()), write it as a file to a temporary location and use this file for the other call.

    This way I don't have to bother with content that is only contained in jars or is located somewhere depending on the web container I'm currently using.

    0 讨论(0)
  • 2020-12-16 03:08

    If you need this in a servlet then use getServletContext().getRealPath("/filepathInContext")!

    0 讨论(0)
提交回复
热议问题