我能够获取目录的文件名,但我无法删除它们
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.util.* ,java.text.* , java.io.*,java.io.File" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String files;
boolean issuccess=true;
//out.println("hi ");
String strDirectoy3=config.getServletContext().getRealPath("/");
//File file = new File("D:\\Test\\hireminibusandcoach.co.uk\\ROOT\\administrator"); FileInputStream in = new FileInputStream("c:/a.txt");
try{
File file = new File(strDirectoy3);
File[] listOfFiles = file.listFiles();
for (int i = 0; i <2; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
out.println(listOfFiles[i].toString());
issuccess=new File(files).delete();
}
}
out.println(" /n Deletion "+issuccess);
}catch(Exception e){
out.println(e);
}
%>
</body>
</html>
答案 0 :(得分:0)
首先,JSP不是一个做这样事情的好地方。然后第二件事是你正在使用 JDK7 。切换到NIO.2 API
它是好的,它会在旧文件API失败的情况下抛出异常。所以,你应该尝试这样做NIO.2 API
跟随:
try
{
Path path = file.toPath();
Files.delete(path);
}
catch (NoSuchFileException x)
{
System.err.format("%s: no such" + " file or directory%n", path);
}
catch (DirectoryNotEmptyException x)
{
System.err.format("%s not empty%n", path);
}
catch (IOException x)
{
// File permission problems are caught here.
System.err.println(x);
}
答案 1 :(得分:0)
请确保运行Web服务器的用户有权删除这些文件。什么父目录为canWrite()方法返回?