2016-04-09 15:05:51|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:Java, 文件操作|来源:唯设编程网
/**
* 递归删除目录下的所有文件及子目录下所有文件
* @param dir 将要删除的文件目录
* @return boolean Returns "true" if all deletions were successful.
* If a deletion fails, the method stops attempting to
* delete and returns "false".
*/
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
//递归删除目录中的子目录下
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
File类的delete方法可以直接删除指定的目录,但如果该目录还包含子目录,删除会失败,所以我们先在目录删除方法deleteDIR中递归逐级删除子目录,最后删除与参数对应的目录。
/**
* 删除指定路径的文件
* @param sPath
*/
public static boolean deleteFile(String sPath){
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
Java的文件删除比较简单,直接调用File类的delete方法执行删除即可,为安全起见,我们先调用了File的isFile方法检测参数路径对应的是否是文件,并且使用了File的exists检测对应文件是否存在。
/**
* 在磁盘创建文件
* @param file
* @return
* @throws com.vcsos.dic.myengdic.utility.exception.NormalException
*/
public static boolean createFile(File file) throws NormalException {
if(file==null)
throw new NormalException("错误:无法根据空对象无法创建文件!",new NullPointerException());
File parentDIR=new File(file.getParent());
if(!parentDIR.isDirectory())
createDirectory(parentDIR);
if(!file.exists())
try {
return file.createNewFile();
} catch (IOException e) {
throw new NormalException("错误:创建文件时发生异常!",new NullPointerException());
}
return false;
}
创建文件使用File类的createNewFile即可,因为传入的路径对应父母了可能不存在,所以我们先使用了File的getParent得到文件所在的目录,然后调用了File的isDirectory检测对应目录是否存在,如果目录不存在,我们就调用createDirectory方法先创建对应的目录。