kasiencja
asked on
Java: Deleting files that start with a specific string.
Hey,
What would be the most efficient way of deleting files from a directory that start with a specific string. For example:
String startString = “300”;
Than all files that start with 300 and l300 (that's lower "L" and 300) will be deleted.
Thanks,
Kate
What would be the most efficient way of deleting files from a directory that start with a specific string. For example:
String startString = “300”;
Than all files that start with 300 and l300 (that's lower "L" and 300) will be deleted.
Thanks,
Kate
ASKER
I was hoping I could use something like FilenameFilterEx, however through trial and error I found out that the filter only works for file extensions.
I tested this and it seems to do what you're asking:
-------------------------- ---------- ---------- ---------- ---------- ---------- -
import java.io.*;
public class dir {
static private String[] files;
static File dir=new File("./");
public static void main(String[] args) {
files=dir.list();
for(int i=0;i<files.length;i++){
System.out.println(files[i ]);
if(files[i].toString().mat ches("^l30 0.*|^300.* ")){
File temp=new File(files[i]);
temp.delete();
System.out.println("Delete d: "+files[i]);
}
}
}
}
-------------------------- ---------- ---------- ---------- ---------- ---------- -
--------------------------
import java.io.*;
public class dir {
static private String[] files;
static File dir=new File("./");
public static void main(String[] args) {
files=dir.list();
for(int i=0;i<files.length;i++){
System.out.println(files[i
if(files[i].toString().mat
File temp=new File(files[i]);
temp.delete();
System.out.println("Delete
}
}
}
}
--------------------------
That's for the current directory (./), and I guess the .toString() is unnecessary...
I didn't really think about why you would want to do this, but it would be much more efficient to weite a shell (or batch) script to do this at the os level.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
2. loop through each file and check the file name starts with the string or 'l' + string
3. true --> delete it
4. false --> continue