我在 jboss 指定的文件夹中保存了一些 .pdf 文件。
现在我想要的是在用户结束应用程序中的 session 后删除这些文件。
最佳答案
只需注册HttpSessionListener并在 session 销毁时以与保存临时文件相同的方式删除临时文件。
只需将创建的文件/文件夹的绝对路径保留在 session 中的某个位置,并在 session 销毁时删除完整的文件夹/文件。
web.xml:
<web-app ...>
<listener>
<listener-class>com.x.y.z.MySessionListener</listener-class>
</listener>
</web-app>
HttpSessionListener:
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent e) {
System.out.println("sessionCreated");
}
@Override
public void sessionDestroyed(HttpSessionEvent e) {
System.out.println("sessionDestroyed");
// delete the file in the same way you have saved it there
// String absolutePath = (String) e.getSession().getAttribute("pdfPath");
// File file = new File(absolutePath);
// if(file.exists()){ file.delete(); }
}
}
关于java - 如何删除临时文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23815552/