Gabriel
Gabriel

Reputation: 97

Deleting a file with similar names in Java

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

Answers (2)

3yakuya
3yakuya

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

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726589

This is a relatively straightforward exercise. Here are the things that you need to know to do understand what to do:

  • A directory is represented by a File object. Create a File object for the directory that you want to list
  • The listFiles() call produces an array of all files in the directory
  • The length() method returns the size of the file
  • The delete() method deletes the file

Your 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

Related Questions