Trying to update the file in src/web/prod folder (jsp)

天涯浪子 提交于 2019-12-24 11:22:17

问题


I am using jboss, eclipse and svn together. I have to files in my test folder: test/create.jsp and test/data.txt . What I want to do is when I call my create.jsp it will update my data.txt . Obviously I want my data.txt to stay where it is as other scripts are tryong to read from it.

I have tried dozens of new ways to put the path to my File object but for some reason it creates the file under jboss war folders.

Tried:

ServletContext app = getServletContext();
String path1 = app.getRealPath("/");
File f = new File(path1);
// AND
File f = new File("../../data.txt");

回答1:


Assuming that /test folder is located in the webcontent, then you need the following:

String absolutePath = getServletContext().getRealPath("/test/data.txt");
File file = new File(absolutePath);

or

String webcontentRoot = getServletContext().getRealPath("/");
File file = new File(webcontentRoot, "test/data.txt");

Do you see it? The Java IO only understands local disk file system paths, not URL's or paths outside the context. The ServletContext#getRealPath() is to be used to convert a relative web path to an absolute local disk file system path which in turn can be used further in the usual Java IO stuff. You should never use relative paths in Java IO stuff. You will be dependent on the current working directory which may differ per environment/situation.

That said, you normally don't want to write files to the webcontent. They will get lost whenever you redeploy the WAR. Rather create a fixed disk file system path somewhere else outside the webapp and make use of it. Or even better, make use of an independent SQL database :)



来源:https://stackoverflow.com/questions/2046265/trying-to-update-the-file-in-src-web-prod-folder-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!