title: Delete all files with an extension using Java
body: <p>I'm (relatively) new to Java and I'm trying to implement a .jar that runs a list of commands that in Windows XP's command prompt it would be:</p>
  <pre><code>cd\
  cd myfolder
  del *.lck /s
  </code></pre>
  <p>My (failed) attempt:</p>
  <pre><code>// Lists all files in folder
  File folder = new File(dir);
  File fList[] = folder.listFiles();
  // Searchs .lck
  for (int i = 0; i &lt; fList.length; i++) {
      String pes = fList.get(i);
      if (pes.contains(&quot;.lck&quot;) == true) {
          // and deletes
          boolean success = (new File(fList.get(i)).delete());
      }
  }
  </code></pre>
  <p>I screwed somewhere around that &quot;get(i)&quot;, but I think I'm pretty close to my goal now.</p>
  <p>I ask for your help and thank you very much in advance!</p>
  <hr />
  <p><strong>EDIT</strong></p>
  <p>Alright! Many thanks, everybody. With the 3 suggested modifications I ended up with:</p>
  <pre><code>// Lists all files in folder
  File folder = new File(dir);
  File fList[] = folder.listFiles();
  // Searchs .lck
  for (int i = 0; i &lt; fList.length; i++) {
      String pes = fList[i];
      if (pes.endsWith(&quot;.lck&quot;)) {
          // and deletes
          boolean success = (new File(fList[i]).delete());
      }
  }
  </code></pre>
  <p>And now it works!</p>
  <p>2022 version:</p>
  <pre class="lang-java prettyprint-override"><code>public static boolean deleteAllFilesWithSpecificExtension(String pathToDir, String extension) {
          boolean success = false;
          File folder = new File(pathToDir);
          File[] fList = folder.listFiles();
          for (File file : fList) {
              String pes = file.getName();
              if (pes.endsWith(&quot;.&quot; + extension)) {
                  success = (new File(String.valueOf(file)).delete());
              }
          }
          return success;
      }
  </code></pre>