整理的一些用到过的工具类,本文为文件操做相关。不是很全......java
publicclassFileUtils { /** * 删除指定的目录或文件 * * @param path 要删除的目录或文件 * @return 删除成功返回 true,不然返回 false。 */ publicstaticbooleandeleteFolder(String path) { booleanflag = false; File file = newFile(path); // 判断目录或文件是否存在 if(file.exists()) { // 判断是否为文件 if(file.isFile()) { // 为文件时调用删除文件方法 returndeleteFile(path); } else{ // 为目录时调用删除目录方法 returndeleteDirectory(path); } } else{ returnflag; } } /** * 删除单个文件 * * @param path 要删除文件的文件名 * @return 单个文件删除成功返回true,不然返回false */ publicstaticbooleandeleteFile(String path) { booleanflag = false; File file = newFile(path); // 路径为文件且不为空则进行删除 if(file.isFile() && file.exists()) { file.delete(); flag = true; } returnflag; } /** * 删除目录以及目录下的文件 * * @param path 要删除目录的文件路径 * * @return 目录删除成功返回true,不然返回false */ publicstaticbooleandeleteDirectory(String path) { // 若是path不以文件分隔符结尾,自动添加文件分隔符 if(!path.endsWith(File.separator)) { path = path + File.separator; } File dirFile = newFile(path); // 若是dir对应的文件不存在,或者不是一个目录,则退出 if(!dirFile.exists() || !dirFile.isDirectory()) { returnfalse; } booleanflag = true; File[] files = dirFile.listFiles(); // 删除文件夹下的全部文件(包括子目录) for(inti = 0; i < files.length; i++) { // 删除子文件 if(files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if(!flag) break; } else{ // 删除子目录的递归调用,循环删除 flag = deleteDirectory(files[i].getAbsolutePath()); if(!flag) break; } } if(!flag) returnfalse; // 删除当前目录 if(dirFile.delete()) { returntrue; } else{ returnfalse; } } /** * 复制目录 * * @param oldPath * 须要复制的目录 * @param newPath * 目标目录 */ publicstaticbooleancopyDirectory(String oldPath, String newPath) { BufferedReader br = null; BufferedWriter bw = null; try{ (newFile(newPath)).mkdirs(); // 若是目录不存在 则创建新目录 File a = newFile(oldPath); String[] file = a.list(); File temp = null; for(inti = 0; i < file.length; i++) { if(oldPath.endsWith(File.separator)) { temp = newFile(oldPath + file[i]); } else{ temp = newFile(oldPath + File.separator + file[i]); } if(temp.isFile()) { br = newBufferedReader(newInputStreamReader( newFileInputStream(temp))); bw = newBufferedWriter(newOutputStreamWriter( newFileOutputStream(newPath + File.separator + (temp.getName()).toString()))); String data; while((data = br.readLine()) != null) { bw.write(data, 0, data.length()); } bw.flush(); } if(temp.isDirectory()) {// 若是是子文件夹 copyDirectory(oldPath + File.separator + file[i], newPath + File.separator + file[i]); } } returntrue; } catch(Exception e1) { System.out.println("复制整个文件夹内容操做出错"); e1.printStackTrace(); returnfalse; } finally{ try{ if(br != null) { br.close(); } if(bw != null) { bw.close(); } } catch(Exception e2) { } } } /** * * 测试方法 * */ publicstaticvoidmain(String[] args) { FileUtils.deleteFolder("E:/testFolder"); } }