62,614
社区成员
发帖
与我相关
我的任务
分享
public class DeleteHTMLFile {
/**
* @param id
* @return 该方法用于删除指定文件夹下的指定文件 1.得到完整的文件名 2.得到文件相对路径 3.找到文件的父文件夹的位置
* 4.查找比对该文件名的文件,并删除 5.若删除成功,返回true
*
*/
public static boolean delete(HttpServletRequest request, String id,
String ctime) {
boolean b = false;
// 需要删除的文件名
try {
String filename = "/news" + id + ".html";
String filePath = request.getServletContext().getRealPath(
"/News_Html");
// 得到文件存在的文件夹名
//取得创建时间的年月,就是文件夹名
String folder = ctime.replace("-", "").substring(0, 6);
//拼接文件所在目录的完整路径
String allPath = filePath + "/" + folder;
System.out.println("文件路径" + filePath);
//得到整个文件的路径
String filePathAndName = allPath + filename;
System.out.println("文件的路径===" + filePathAndName);
//对反斜杠进行转换
String newfilePath = filePathAndName.replace("\\", "/");
System.out.println("将要删除的文件" + newfilePath);
//再次转换成双反斜杠
String realPath = newfilePath.replace("/", "\\\\");
System.out.println("最终删除路径" + realPath);
//删除部分
File myDelFile = new File(realPath);
//判断文件是否存在
if (myDelFile.exists()) {
b = myDelFile.delete();
}
if (b) {
System.out.println("删除文件成功");
} else {
System.out.println("删除文件出错");
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("删除文件出错");
e.printStackTrace();
}
return b;
}
if (myDelFile.exists()) {
b = myDelFile.delete();
}else{
打印文件不存在
}
String allPath = filePath+"/" + folder;
,修改了之后,还是有错误,我的路径是取出来了的,控制台上打印输出的就是取出来的路径