package com.util;
import java.io.File;
public
class FileUtil {
private static FileUtil
instance = new FileUtil();
public static FileUtil getInstance(){
return instance;
}
public FileUtil() {
// TODO Auto-generated constructor stub
}
/**
* 删除文件
*
* @param filePathAndName
*/
public void delFile(String filePathAndName) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myDelFile = new File(filePath);
myDelFile.delete();
} catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
http://www.javalearns.com/
/**
* 删除文件夹
*
* @param folderPath
*/
public void delFolder(String folderPath) {
try {
delAllFile(folderPath);// 删除文件夹中所有的文件
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
myFilePath.delete();
} catch (Exception e) {
System.out.println("删除文件夹操作出错");
e.printStackTrace();
}
}
/**
* 删除文件中的所有文件
*
* @param folderPath
*/
private void delAllFile(String path) {
// TODO Auto-generated method stub
File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);// 再删除空文件夹
}
}
}
http://www.javalearns.com/
/**
* 测试删除功能
*
* @param args
*/
public static void main(String[] args) {
String str = "E:\\test\\";
File file = new File(str);
//File fileb = new File("E:\test");
FileUtil fp = new FileUtil();
if (fp.deletedir(file)) {
System.out.println("success");
} else {
System.out.println("
failed!");
}
}
/**
* 删除文件
* @param file
* @return
*/
public boolean deletefile(File f) {
if (f.isFile())
f.delete();
return true;
}
/**
* 删除目录
* @param folder
* @return
*/
public boolean deletedir(File f) {
if (f.isDirectory()) {
File[]
files = f.listFiles();
if(files != null){
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
deletedir(files[i]);
else
deletefile(files[i]);
}
}
}
f.delete();
return true;
}
}
文章转载自 http://www.javalearns.com/Html/?1561.html
更多Java学习文章请访问 Java免费学习网 http://www.javalearns.com