Java 创建目录运行时 WebApp
我有一个 Java SEAM2 中的 Web 应用程序在 JBOSS 上运行。
在我的应用程序中,我尝试动态/运行时创建目录。
发生的情况是,这些目录被创建,但是当我尝试将文件写入其中时,它会抛出空指针异常。 所以重新启动我的服务器,然后一切正常,为什么呢?
if(ClassName.class.getClassLoader().getResource("roles/" + role ) == null)
{
//create directory with role name
String rolePath = ClassName.class.getClassLoader().getResource("roles").getPath();
rolePath = rolePath.substring(1, rolePath.length());
rolePath = rolePath.replace("/", "\\");
rolePath = rolePath + "\\" + role;
if( !(new File(rolePath).mkdir()))
{
this.addMessage(FacesMessage.SEVERITY_ERROR, "Error Creating Role Directory");
return;
}
}
if(ClassName.class.getClassLoader().getResource("roles/" + role + "/" + app ) == null)
{
String appPath = ClassName.class.getClassLoader().getResource("roles/" + role).getPath();
appPath = appPath.substring(1, appPath.length());
appPath = appPath.replace("/", "\\");
appPath = appPath + "\\" + app;
File appFolder = new File(appPath);
if( !(appFolder.mkdir()))
{
this.addMessage(FacesMessage.SEVERITY_ERROR, "Error Creating Role Directory");
return;
}
}
我的猜测是,由于我使用的是 getClassLoader,因此它不会使用创建的新文件进行更新
I have a webapp in Java SEAM2 running on JBOSS.
In my application I am trying to create directories on the fly / runtime.
Well what happens is that these directories get created, but when I try to write a file into them it throws a null pointer exception.
So restarted my server and all works well then, why is it ?
if(ClassName.class.getClassLoader().getResource("roles/" + role ) == null)
{
//create directory with role name
String rolePath = ClassName.class.getClassLoader().getResource("roles").getPath();
rolePath = rolePath.substring(1, rolePath.length());
rolePath = rolePath.replace("/", "\\");
rolePath = rolePath + "\\" + role;
if( !(new File(rolePath).mkdir()))
{
this.addMessage(FacesMessage.SEVERITY_ERROR, "Error Creating Role Directory");
return;
}
}
if(ClassName.class.getClassLoader().getResource("roles/" + role + "/" + app ) == null)
{
String appPath = ClassName.class.getClassLoader().getResource("roles/" + role).getPath();
appPath = appPath.substring(1, appPath.length());
appPath = appPath.replace("/", "\\");
appPath = appPath + "\\" + app;
File appFolder = new File(appPath);
if( !(appFolder.mkdir()))
{
this.addMessage(FacesMessage.SEVERITY_ERROR, "Error Creating Role Directory");
return;
}
}
My guess is that since I am using getClassLoader it is not getting updated with the new files created
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从类加载器创建一个基于资源路径的文件夹是一个坏主意(你永远不知道源/文件夹来自哪里)
更好的方法是,使用 java.io.temp 文件夹,或使用配置来了解系统中的存储库文件夹。
It is a bad idea to create a folder base a resource path from class loader (you never where is the srouce/folder from)
better way are, use java.io.temp folder, or use a configuration to know get repository folder in your system.