Javaservlet:删除临时文件
我正在开发一个JavaServlet,它创建一个临时文件用于会话。在会话结束时(即,用户“注销”),我需要删除临时文件,然后将用户重定向到初始(“登录”)页面。重定向工作正常,但临时文件保持不变 我认为它与文件的路径有关,但我不太确定是什么。我在会话启动时创建文件:Javaservlet:删除临时文件,java,tomcat,servlets,Java,Tomcat,Servlets,我正在开发一个JavaServlet,它创建一个临时文件用于会话。在会话结束时(即,用户“注销”),我需要删除临时文件,然后将用户重定向到初始(“登录”)页面。重定向工作正常,但临时文件保持不变 我认为它与文件的路径有关,但我不太确定是什么。我在会话启动时创建文件: String path = request.getSession().getServletContext().getRealPath("/"); File file = File.createTempFile("getter", "
String path = request.getSession().getServletContext().getRealPath("/");
File file = File.createTempFile("getter", ".html", new File(path + "/tmp/"));
然后,在结束会话时,我会:
file.delete();
我知道file.deleteOnExit()
,但是。。。何时退出servlet?也许我有点困惑,但我一定会感谢您的帮助
提前谢谢你
编辑
下面是一些细节:
正如我所说,目前我使用的是一个servlet,没有处理会话。我同意@Joop的说法,我需要实现会话,但目前我只想做一些简单的测试
因此,我的servlet处理GET
和POST
请求。我在POST
请求中使用一个标志来调用一个内部函数,该函数将该文件(在类中声明为private file;
)实例化为一个新的临时文件。在连续调用时,将填充并保存文件。在用户看到的页面中,我有一个指向servlet(即“this”)的锚,将一个标志作为参数传递,一个指示“注销”的标志。然后调用另一个内部函数,该函数删除先前实例化的文件
如果这是一个评估问题,我将实施经理并公布我的调查结果
编辑2
我实现了一个HttpSessionListener
,看起来一切正常。现在,在创建会话时,我在先前声明的目录中实例化了一个文件(请注意,它不是临时文件,我使用file file file=new file(path+“/tmp/”+req.getSession().getId()+“.html”);
因此文件名等于会话ID)。然后我向会话添加一个属性,其值是文件的完整路径。我将一如既往地填充我的文件,当用户选择注销时,我将使会话无效。然后,在侦听器中,我检索文件的路径,因此可以获取指向该文件的指针:
String fname = ev.getSession().getAttribute("filename").toString();
File f = new File(fname);
f.delete();
因此,现在我得到的消息是肯定的,我的意思是f.delete()
返回true,然后我执行f.exists()
并得到false
。所以应该没问题。但是,这些文件实际上是存在的,也就是说,它们仍然存在于磁盘上
我可以试试@A4L提供的例子。我做错什么了吗?当用户注销时,请确保在尝试删除文件之前已关闭该文件,并检查
文件#delete()
返回的内容
@Test
public void createTempFile() throws IOException {
File tf = File.createTempFile("hello", ".tmp", new File("."));
FileOutputStream fos = new FileOutputStream(tf);
fos.write("Hello, Temp!".getBytes());
Assert.assertTrue(tf.delete()); // fails because the file could not be deleted
// and delete() returns false
}
vs.
@Test
public void createTempFile() throws IOException {
File tf = File.createTempFile("hello", ".tmp", new File("."));
FileOutputStream fos = new FileOutputStream(tf);
fos.write("Hello, Temp!".getBytes());
fos.close();
Assert.assertTrue(tf.delete()); // passes, file deleted
}
当VM退出时,该文件将被删除,这在tomcat关闭时发生。所以这对用户注销没有帮助
编辑
确保每个用户和跨多个请求只有一个文件。我建议您按照Joop的建议使用一个SessionListener
,在调用时创建文件,并使用一个已知的键将其放入会话中,您可以使用。当您注销调用时,将调用Listner方法,然后您可以从会话中获取文件并将其删除
简单示例(仅限doGet,不含SessionListener)
导入java.io.BufferedReader;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileWriter;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.PrintWriter;
导入java.util.ArrayList;
导入java.util.Date;
导入java.util.List;
导入javax.servlet.annotation.WebServlet;
导入javax.servlet.http.HttpServlet;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入javax.servlet.http.HttpSession;
@WebServlet(urlPatterns=“/ptf.html”)
公共类PopulateTempFile扩展了HttpServlet{
私有静态最终长serialVersionUID=-144949663400032218L;
私有静态类TempFilePopulator{
私有文件tf=null;
公共TempFilePopulator(字符串rootDir)引发IOException{
tf=File.createTempFile(“hello”、“.tmp”、新文件(rootDir));
}
公共void填充(字符串行)引发IOException{
FileWriter fw=新的FileWriter(tf,true);
fw.写入(第+行“\n”);
fw.close();
}
公共列表getContent()引发IOException{
列表行=新的ArrayList();
BufferedReader br=新的BufferedReader(新的InputStreamReader(新文件InputStream(tf));
弦线;
而(null!=(line=br.readLine()){
行。添加(行);
}
br.close();
回流线;
}
公共布尔deleteTempFile(){return tf.delete();}
公共字符串toString(){return tf.getAbsolutePath();}
}
@凌驾
public void doGet(HttpServletRequest请求、HttpServletResponse响应)引发IOException{
HttpSession session=request.getSession();
TempFilePopulator tfp=(TempFilePopulator)session.getAttribute(“TempFilePopulator”);
response.setContentType(“text/html”);
PrintWriter out=response.getWriter();
out.println(“”);
out.println(“”);
out.println(“|”);
out.println(“”);
字符串logout=request.getParameter(“logout”);
如果(“真”。等于(注销)){
如果(tfp!=null){
if(tfp.deleteTempFile()){
日志(“临时文件”’+tfp+“‘已删除’);
}否则{
日志(“无法删除临时文件”“+tfp+””);
}
}
session.invalidate();
}否则{
如果(tfp==null){
tfp=新的TempFilePopulator(请求
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(urlPatterns = "/ptf.html")
public class PopulateTempFile extends HttpServlet {
private static final long serialVersionUID = -144949663400032218L;
private static class TempFilePopulator {
private File tf = null;
public TempFilePopulator(String rootDir) throws IOException {
tf = File.createTempFile("hello", ".tmp", new File(rootDir));
}
public void populate(String line) throws IOException {
FileWriter fw = new FileWriter(tf, true);
fw.write(line + "\n");
fw.close();
}
public List<String> getContent() throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(tf)));
String line;
while(null != (line = br.readLine())) {
lines.add(line);
}
br.close();
return lines;
}
public boolean deleteTempFile() { return tf.delete(); }
public String toString() { return tf.getAbsolutePath(); }
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
TempFilePopulator tfp = (TempFilePopulator) session.getAttribute("tempfilepopulator");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<a href=\"" + request.getServletContext().getContextPath()
+ request.getServletPath() + "\">Refresh</a>");
out.println(" | ");
out.println("<a href=\"" + request.getServletContext().getContextPath()
+ request.getServletPath() + "?logout=true\">Logout</a>");
String logout = request.getParameter("logout");
if("true".equals(logout)) {
if(tfp != null) {
if(tfp.deleteTempFile()) {
log("Temp file '" + tfp + "' deleted.");
} else {
log("Unable to delete temp file '" + tfp + "'");
}
}
session.invalidate();
} else {
if(tfp == null) {
tfp = new TempFilePopulator(request.getServletContext().getRealPath("/"));
log("Temp file '" + tfp + "' created.");
session.setAttribute("tempfilepopulator", tfp);
}
tfp.populate(new Date().toString());
out.println("<p>Content of temp file</p>");
List<String> lines = tfp.getContent();
for(String line : lines) {
out.write(line);
out.write("<br/>");
}
}
out.println("</html>");
}
}
Creates a new empty file in the specified directory, using the given prefix and
suffix strings to generate its name. If this method returns successfully then
it is guaranteed that:
The file denoted by the returned abstract pathname did not exist before this
method was invoked and ,
Neither this method nor any of its variants will return the same abstract
pathname again in the current invocation of the virtual machine.
This method provides only part of a temporary-file facility. To arrange
for a file created by this method to be deleted automatically, use the
deleteOnExit() method.
path = request.getSession().getServletContext().getRealPath("/");
File file = File.createTempFile("getter", ".html");