JSP下载后删除文件

时间:2013-01-16 08:41:06

标签: java jsp

使用以下代码下载文件

<%@page import="java.nio.channels.OverlappingFileLockException"%>
<%@page import="java.nio.channels.FileLock"%>
<%@page import="java.nio.channels.FileChannel"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page contentType="application/octet-stream"%>
<%@page pageEncoding="UTF-8"%>
<%@page language="java" import="java.io.*,java.net.*,java.util.*,javax.servlet.*"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>JSP Page</title>
    </head>
    <body>
        <%

        BufferedInputStream filein = null;
        BufferedOutputStream output = null;
        try {

            File file = new File("d:/ttt.mp3"); // path of file
            if (file.exists()) {


                byte b[] = new byte[2];        
                int len = 0;
                filein = new BufferedInputStream(new FileInputStream(file));
                output = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/force-download");
                response.setHeader("content-Disposition", "attachment; filename=Backup.gz");
                response.setHeader("content-Transfer-Encoding", "binary");
                while ((len = filein.read(b)) > 0) {
                    output.write(b, 0, len);

                    output.flush();

                 //   output.close();

                }


                Calendar present = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String a = sdf.format(present.getTime());
                String ip = request.getRemoteAddr();
                String mail = session.getAttribute("emailid").toString();
                try {
                    PreparedStatement pst = null;
                    String connectionURL = "jdbc:mysql://localhost/logapp_log";
                    Connection connection = null;
                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                    connection = (Connection) DriverManager.getConnection(connectionURL, "root", "nic@123");
                    String query = "insert into logapp_log_table(uname,date_time,user_ip) values ('" + mail + "','" + a + "','" + ip + "')";
                    pst = connection.prepareStatement(query);
                    pst.executeUpdate();
                    pst.close();
                    connection.close();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else {
                session.setAttribute("Ferror", "File not available Or Deleted");
                getServletContext().getRequestDispatcher("/link.jsp").forward(request, response);
            }

        } catch (Exception ex) {
            System.out.print(ex.getMessage());
        }

    %>
</body>

这段代码工作得很好...... 以及下载后删除该文件的代码......

File file = new File("d:/ttt.mp3");
       if(file.exists()) { 

        if (file.delete()) {

            System.out.println("File Deleted");
            session.setAttribute("Ferror","Deleted");
            getServletContext().getRequestDispatcher("/link.jsp").forward(request, response);
            response.sendRedirect("login.jsp");
        } else {
            System.out.println("Delete failed");
            session.setAttribute("Ferror","Under Process");
            getServletContext().getRequestDispatcher("/link.jsp").forward(request, response);
        }
       }
       else {


           session.setAttribute("Ferror","File not available Or Deleted");
           getServletContext().getRequestDispatcher("/link.jsp").forward(request, response);
       }

删除代码工作正常,当我删除文件,然后我下载 我需要当用户下载文件后,他也可以在下载后删除该文件,但我的下载代码无效..它打印删除失败的其他代码

请给我删除该文件的方法..或者下载完成后立即删除文件的任何其他方式。

2 个答案:

答案 0 :(得分:2)

您打开文件进行阅读,忘记关闭它。由于您在Windows上锁定打开的文件,因此无法将其删除。将文件发送到客户端后,在finally块中调用filein.close()。然后尝试删除它。我希望这会奏效。

在linux上它不会发生! :)

答案 1 :(得分:2)

正如@AlexR所说,你应该先将文件关闭,然后再将其删除。

try{
    filein = new BufferedInputStream(new FileInputStream(file));
    //do your work
}finally{
    if(filein!=null){
        filein.close(); //close the file
    }
}

关闭文件输入流以释放Unix下的文件处理程序,如OS。