- package file;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class FileTraversalDemo {
- public static void main(String[] args) {
- boolean state = true;
- while(state){
- System.out.println("请输入文件目录:");
- BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
- String path = null;
- try {
- path = bf.readLine(); //输入的文件路径
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- File f = new File(path);
- if(f.isDirectory()){
- state = false;
- Traverse.remove(f);
- }else{
- System.out.println("路径输入有误!!");
- }
- }
- }
- }
- class Traverse {
- public static void remove(File f){
- if(f.isDirectory()){
- File[] farr=f.listFiles();
- for(int i=0;i<farr.length;i++){
- remove(farr[i]);
- }
- //System.out.println(f+":"+f.delete()); //删除目录
- }
- else{
- String leixing = f.getName().substring(f.getName().lastIndexOf("."));
- if(".bak".equals(leixing)){
- if(f.delete()){
- System.out.println(f+" 文件删除成功!");
- }else{
- System.out.println(f+" 文件删除失败!");
- }
- }
- }
- }
- }
复制代码 |