Create a file and store in Java web application folder

前端 未结 2 1056
伪装坚强ぢ
伪装坚强ぢ 2021-01-06 03:55

I would like to create an xml file and store in a folder within my spring Mvc web application.

I can get the root of my application with request.getContextPath

相关标签:
2条回答
  • 2021-01-06 04:37

    One solution is to bundle the XML with the clases in the JAR/WAR and then use the getResourceAsStream() to leverage the ClassLoader to locate the file.

    If I put the file foo.xml with the classes in com/stackoverflow/example, I could then locate the resources from objects in that bundle with

    InputStream is = MyClass.getResourceAsStream( "com/stackoverflow/example" );

    and from here process the file with a XML parser or whatever else you wanted to do to read the file.

    0 讨论(0)
  • 2021-01-06 04:55

    You want to do this.

    First, you need to get the ServletContext. I don't know how this is done in Spring MVC, but it's there somewhere.

    Then you can do:

    ServletContext ctx = getServletContextFromSpringSomehow();
    String path = ctx.getRealPath("/folder/filename.txt");
    FileWriter fw = new FileWriter(path);
    

    The key here is ServletContext.getRealPath. It gives you the local file system path of a resource from within your webapp. Observer that you use "/" here, as it's a URL, not a file name. The container will give you a valid file name in return. Note, this only works if your container explodes your WAR, or you deploy an exploded WAR. If the WAR is NOT exploded, you will get a null back from the container.

    Also note, this WILL work for non-existent files. The container does not check for the actual existence of the file. But it will be up to you to actually create any missing intermediate directories, etc.

    Finally, of course, that even if you get a file path back, doesn't mean you can actually write to that path. That's a OS permission issue outside of the scope of the container.

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