Java基础之查找文件名&删除文件夹和文件
2015-11-02 20:23
507 查看
/** * @description 在磁盘上有一个文件夹:temp,该文件夹中有多个子文件和子文件夹,在子文件夹中还有其 * 子文件夹和子文件(嵌套),请写一个程序统计出temp文件夹中所有的后缀名是.txt的文本 * 文件(包括直接或间接),并打印出它们的名字清单。 * @author Guan * @date 2015-11-2 上午11:40:34 * @version 1.0 */ public class FileTest { /** * 1.查找文件名 */ /** * @description 通过目录遍历文件名 * @param file * @param temp */ public static void queryFile(File file, String temp) { // 是文件的情况 if (file.isFile()) { System.out.print("文件 :" + file.getName() + "\t"); } else { // 是目录的情况 File[] files = file.listFiles(); for (File fileTemp : files) { if (fileTemp.isDirectory()) { System.out.println(temp + "目录 :" + fileTemp.getName() + "\t"); queryFile(fileTemp, temp + "\t"); } else { System.out.println(temp + "文件 :" + fileTemp.getName() + "\t"); } } } } /** * 2.删除文件夹和文件 */ /** * @description 删除文件夹 * @param folderPath */ public static void delFolder(String folderPath) { try { delAllFile(folderPath); // 删除完里面所有内容 String filePath = folderPath; filePath = filePath.toString(); java.io.File myFilePath = new java.io.File(filePath); myFilePath.delete(); // 删除空文件夹 } catch (Exception e) { e.printStackTrace(); } } /** * @description 删除指定文件夹下所有文件 * param path 文件夹完整绝对路径 * @return */ public static boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } 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]); flag = true; } } return flag; } public static void main(String[] args) { // newFile中输入文件夹路径 new File(path); // System.getProperty("user.dir")); 返回的是工程的根目录,D:\2.eclipse\Test File file = new File(System.getProperty("user.dir") + "/inoroutput/file"); // 查找文件名 queryFile(file, ""); // 删除文件夹和文件 delFolder(System.getProperty("user.dir") + "/inoroutput/file"); System.out.println("deleted"); } }
相关文章推荐
- Java 中泛型的全面解析
- java String的使用
- java---表、栈和队列
- java知识体系
- Java 8中的增强的Arrays
- java基础之对properties配置文件的读写操作
- SpringMVC
- SpringIOC_容器的类扫描注解
- spring 读取操作系统上的文件
- java怎么实现两个对象内容的交换
- Java list容器
- Eclipse 编写java时, 出现的库访问限制问题
- JAVA 数组作业——动手动脑以及课后实验性问题
- Eclipse下Java链接MySQL数据库
- 关于Java交换两个对象的问题
- java线程基础知识和小案例
- eclipse设置和优化
- Java版本
- Java数据类型、操作符、表达式
- Java接口