How to access a file under WEB-INF folder in java class

后端 未结 4 805
终归单人心
终归单人心 2020-12-01 16:35

I have a plain java class in a web application and want to read a configuration file under WEB-INF folder. I know the way to access the file if its in the class

4条回答
  •  执笔经年
    2020-12-01 16:42

    hey you all care for context related file loading like application context , web.xml ,config and property file

    Here is how to load a java file any kind of file under WEB-INF but it stored on another stucture like a sub folder reportFile the your file or sub folder again report01--

    fullpath is = /WEB-INF/reportFile/report01/report.xml ,i have tried many possibilities to load and read this xml file ...none of the above worked for me but , here is the trick for future use...

    In Action or inservice class you know interface implementation class no imports that is good part also.

    declare your file object

    File myClass = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getFile());
    System.out.println("Finding calss path first then remove classes from the path "    + myClass.getCanonicalPath().replaceFirst("classes", "")+"reportFIle/report01/reports.xml")
    

    2.Load the path by removing classes from the above and add your specific path

    File f = new File(myClass.getCanonicalPath().replaceFirst("classes", "")+"reportFile/report01/reports.xml")
    

    Then

    you can even parse it using xml parser or do anything

    document = docBuilder.parse(new File(myClass.getCanonicalPath().replaceFirst("classes", "")+"reportFile/report01/reports.xml"));
    

    Cheers!!

提交回复
热议问题