[java tool] A tool that deletes files under the specified path by extension

Common methods that were often used at work before

■ Example of deleting all files under the work file path from the file type (example: * .txt, * .class, . * ())

FindFilesAndDeleter.java


package src.main.java;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
public class FindFilesAndDeleter {
 /**For Log output. */
 static Logger logger = Logger.getLogger(FindFilesAndDeleter.class);
 
 private static final String FILETYPE_ALL = "\\*.\\*|\\*";
 private static final String FILETYPE_SOMEONE = "\\*.[\\w\\d_-]+";
 private static final String STATUS_1 = "1";
 private static final String STATUS_2 = "2";
 private static final String STATUS_3 = "3";
 public static boolean isBlank(String str) {
  int strLen;
  if (str == null || (strLen = str.length()) == 0) {
   return true;
  }
  for (int i = 0; i < strLen; i++) {
   if ((Character.isWhitespace(str.charAt(i)) == false)) {
    return false;
   }
  }
  return true;
 }
 public static String readLineFromConsole() throws IOException{
  String line = new BufferedReader(new InputStreamReader(System.in))
  .readLine();
  return line;
 }
 
 /**
  * @param deleteFileTypes
  * @return 1-NG,2-*.*,3-*.xyz(,*.class...)
  */
 private static String getStatusByInputValueCheck(String deleteFileTypes) {
  String inputFileType = deleteFileTypes.trim();
  String[] typeLst = inputFileType.split(",");
  for (String string : typeLst) {
   String tmp = string.trim();
   Pattern pat = Pattern.compile(FILETYPE_ALL);
   Matcher mat = pat.matcher(tmp);
   if (mat.matches()) {
    return STATUS_2;
   }
  }
  for (String string : typeLst) {
   String tmp = string.trim();
   Pattern pat = Pattern.compile(FILETYPE_SOMEONE);
   Matcher mat = pat.matcher(tmp);
   if (mat.matches()) {
    return STATUS_3;
   }
  }
  return STATUS_1;
 }
 
 private static void goToCleanByRootPath(String rootPath,
   String deleteFileTypes, String status) {
  // 2-*.*,3-*.xyz(,*.class...)
  File file = new File(rootPath);
  if(file.isDirectory()){
   File fileLst[] = file.listFiles();
   for (File file2 : fileLst) {
   if (file2.isDirectory()) {
    logger.info("<Directory>"+file2);
    goToCleanByRootPath(file2.getAbsolutePath(), deleteFileTypes, status);
   } else if(file2.isFile()){
     if (STATUS_2.equals(status)) {
      deleteFile(file2);
     } else if (STATUS_3.equals(status)) {
      if (isDeleteObject(file2, deleteFileTypes)) {
       deleteFile(file2);
      } else {
       logger.info("<File><Not applicable:"+deleteFileTypes+">"+file2);
      }
     }
    }
   }
  } else{
   logger.warn("<Directory>"+rootPath + " is not directory.");
  }
 }

private static boolean isDeleteObject(File file2,String deleteFileTypes) {
  String inputFileType = deleteFileTypes.trim();
  String[] typeLst = inputFileType.split(",");
  for (String string : typeLst) {
   String tmpFileTypeWithoutSpace = string.trim();
   if (file2.getName().trim().endsWith(tmpFileTypeWithoutSpace.substring(1))) {
    return true;
   }
  }
  return false;
 }
 private static void deleteFile(File file2) {
  if (file2.delete()){
   logger.info("<File>"+file2);
  } else {
   logger.info("<File><Delete failure>"+file2);
  }
 }
 /**
  * @param args
  */
 public static void main(String[] args) {
  logger.info("========Start processing========");
  String rootPath = "";
  String deleteFileTypes = "";
  try {
   /******Working file path******/
   System.out.println("Example: C:\\temp");
   System.out.print("Work path:");
   rootPath = readLineFromConsole();
   logger.info("Work path:" + rootPath);
   /******Delete file type******/
   String status = "";
   do{
    if(!isBlank(status)){
     System.out.println("*** input error. plz input again. ***");
     logger.warn("*** input error. plz input again. ***");
    }
    System.out.println("Example:*.txt,*.class,*.*(*)");
    System.out.print("Deleted file type:");
    deleteFileTypes = readLineFromConsole();
    logger.info("Deleted file type:" + deleteFileTypes);
   } while( STATUS_1.equals( (status = getStatusByInputValueCheck(deleteFileTypes))));
   /********Start processing*********/
   logger.info("■ Record output STA");
   goToCleanByRootPath(rootPath, deleteFileTypes, status);
   logger.info("■ Record output END");
  } catch (Exception e) {
   logger.error("Abnormality:" + e);
  } finally {
   logger.info("========Processing Exit========");
  }
 }
}

Log4j.properties


### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %5p %c{1} - %m%n
### direct messages to file mylog.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C\:/Users/kou123label/Desktop/FindTexterLog.log
log4j.appender.file.Append=true
log4j.appender.file.MaxFileSize=20MB
log4j.appender.file.MaxBackupIndex=3
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d %5p %c{1} - %m%n
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%-5p %d [%t] %m%n
log4j.rootLogger=debug, stdout, file

Recommended Posts

[java tool] A tool that deletes files under the specified path by extension
Code that deletes all files of the specified prefix in AWS S3 (Java)
How to save a file with the specified extension under the directory specified in Java to the list
[Java] Divide a character string by a specified character
I made a Diff tool for Java files
[Java] Processes all files under a certain directory
[Swift5] extension that allows UIImage to be specified by a String type URL
Learn the meaning of "passing the PATH" by building a Java development environment on Mac
[Java] I tried to make a maze by the digging method ♪
How to identify the path that is easy to make a mistake