gpt4 book ai didi

Java 创建目录运行时 WebApp

转载 作者:行者123 更新时间:2023-12-01 16:00:54 25 4
gpt4 key购买 nike

我有一个在 JBOSS 上运行的 Java SEAM2 Web 应用程序。

在我的应用程序中,我尝试动态/运行时创建目录。

发生的情况是,这些目录被创建,但是当我尝试向其中写入文件时,它会抛出空指针异常。所以重新启动我的服务器,然后一切正常,为什么呢?

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,因此它不会随着创建的新文件而更新

最佳答案

基于类加载器的资源路径创建文件夹是一个坏主意(你永远不知道源/文件夹来自哪里)更好的方法是,使用 java.io.temp 文件夹,或使用配置来了解系统中的存储库文件夹。

关于Java 创建目录运行时 WebApp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3956799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com