There is a folder, I want to go through all the elements, and if it is a folder, then go into it and continue until the elements run out. If it is a file, then check the file name and, if appropriate, delete it. How can you do?

File directory = new File("C:\\Users\\Admin\\Desktop\\Something\\directory"); File[] files = new File("C:\\Users\\Admin\\Desktop\\Something\\directory").listFiles(); // Graph g = new Graph try{ for(File thisFile : files){ if(thisFile.isFile()) { String data = thisFile.getName(); int FileDay = Integer.parseInt(data.substring(data.length() - 6, data.length() - 4)); int FileMonth = Integer.parseInt(data.substring(data.length() - 9, data.length() - 7)); int FileYear = Integer.parseInt(data.substring(data.length() - 14, data.length() - 10)); if (FileYear * 12 + FileMonth <= year * 12 + nowMonth - month + 1) { thisFile.delete(); } } } } catch(NullPointerException e){ e.printStackTrace(); } 

The code only works for one specified folder, but it needs to check folders inside folders. I thought through Depth First Search to do something, but it did not work out.

  • Use recursion. - Gennady P

1 answer 1

Can so

  public static void main(Strnig[] args) { chkDir(new File("C:\\Users\\Admin\\Desktop\\Something\\directory")); } private void chkDir(File dir){ for (File f : dir.listFiles()){ if(f.isDirectory()){ chkDir(f); }else{ chkFile(f); } } } private void chkFile(File f){ ... }