Reputation: 97
I have like 2 files with almost same name like "myfile_1234.mp4" and "myfile_5678.mp4" in the same directory. One File, say, "myfile_1234.mp4" size is ZERO bytes where as the other file say "myfile_5678.mp4" has some size NOT EQUAL to ZERO (say 32kb). Now I want to delete the 1st File from the Directory but not the other File.
Can we have something like a loop temp pointer to the Files in the Directory and we would then check for Size of file and delete it when its size is ZERO.
Can anyone help me here...?
Upvotes: 2
Views: 796
Reputation: 2672
You can have a file (handle) created like
File myFileOne = new File(path);
File myFileTwo = new File(anotherPath);
Having such handles it is quite easy to check files size or names and delete the files as well. For more info on Java File see: http://docs.oracle.com/javase/6/docs/api/java/io/File.html#File
Upvotes: 4
Reputation: 726589
This is a relatively straightforward exercise. Here are the things that you need to know to do understand what to do:
File
object. Create a File
object for the directory that you want to listlistFiles()
call produces an array of all files in the directorylength()
method returns the size of the filedelete()
method deletes the fileYour code will look like this:
// Reference the directory in which the files reside
File dir = new File("c:/my/test/directory");
// Go through the files in the directory in a loop
for ( File file : dir.listFiles()) {
// Make sure that an entry is a file (it could be a directory)
// and that its size is zero
if (file.isFile() && file.length() == 0) {
// If both conditions are true, delete the empty file
file.delete();
}
}
You can make additional conditions to check if a file has a particular name, extension, etc.
Upvotes: 5