0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

指定ファイル以外を再帰的に削除する

Last updated at Posted at 2024-06-29
Main.java

package main;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class Main {
	String absolutePath = "C:\\Users\\ \\Desktop\\~♪";
	ArrayList<String> deleteFileList = new ArrayList<String>(Arrays.asList(
			".gitignore",
			"Tests.java",
			"LogAspct.java"
			));

    public static void main(String[] args) throws IOException {
    	new Main();
    }
    
    public Main() throws IOException {
    	
        findAllFile(absolutePath);
        deleteEmptyDirectory(absolutePath);
    }

    public List<File> findAllFile(String absolutePath) throws IOException {

        List<File> fileList = new ArrayList<>();

        Stack<File> stack = new Stack<>();
        stack.add(new File(absolutePath));
        while (!stack.isEmpty()) {
            File item = stack.pop();
            if (item.isFile()) {
            	fileList.add(item);
            	deleteFile(deleteFileList, item);
            }

            if (item.isDirectory()) {
        		for (File child : item.listFiles()) {
        			stack.push(child);
        		}
            }
        }

        return fileList;
    }

    public static void deleteEmptyDirectory(String target) {
		 
    	System.out.println(target);
        Stack<File> stack = new Stack<>();
		try {
			File directory = new File(target);
			File[] files = directory.listFiles();
 
			for(File file: files) {
				if (file.isDirectory()) {
					stack.add(file);
					deleteEmptyDirectory(file.getPath());
				}
			}
			
	        while (!stack.isEmpty()) {
	            File file = stack.pop();
		    	System.out.println("dir削除:" + directory.getAbsolutePath());
                ファイル消える~♪ file.delete() 
	        }
		} catch (Exception e) {
			System.out.println(e);
		}
	}
    
    private void deleteFile(List<String> dList, File file) throws IOException  {
    	
    	for(String fileName : dList) {
    		if(file.getAbsolutePath().contains(fileName)) {
    			return;
    		} else {
    		}
    	}
    	System.out.println("ファイル削除:" + file.getAbsolutePath());
        ファイル消える!! file.delete() 
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?