3

I am searching for a sound file in a folder and want to know if the sound file exist may it be .mp3,.mp4,etc.I just want to make sure that the filename(without extension) exists.

eg.File searching /home/user/desktop/sound/a

return found if any of a.mp3 or a.mp4 or a.txt etc. exist.

I tried this:

File f=new File(fileLocationWithExtension);

if(f.exist())
   return true;
else return false;

But here I have to pass the extension also otherwise its returning false always

To anyone who come here,this is the best way I figured out

    public static void main(String[] args) {
    File directory=new File(your directory location);//here /home/user/desktop/sound/
    final String name=yourFileName;  //here a;
            String[] myFiles = directory.list(new FilenameFilter() {
                public boolean accept(File directory, String fileName) {
                    if(fileName.lastIndexOf(".")==-1) return false;
                    if((fileName.substring(0, fileName.lastIndexOf("."))).equals(name))
                        return true;
                    else return false;
                }
            });
   if(myFiles.length()>0)
       System.Out.println("the file Exist");
}

Disadvantage:It will continue on searching even if the file is found which I never intended in my question.Any suggestion is welcome

user2511713
  • 555
  • 3
  • 7
  • 18

7 Answers7

6

This code will do the trick..

public static void listFiles() {

        File f = new File("C:/"); // use here your file directory path
        String[] allFiles = f.list(new MyFilter ());
        for (String filez:allFiles ) {
            System.out.println(filez);
        }
    }
}
        class MyFilter implements FilenameFilter {
        @Override
        //return true if find a file named "a",change this name according to your file name
        public boolean accept(final File dir, final String name) {
            return ((name.startsWith("a") && name.endsWith(".jpg"))|(name.startsWith("a") && name.endsWith(".txt"))|(name.startsWith("a") && name.endsWith(".mp3")|(name.startsWith("a") && name.endsWith(".mp4"))));

        }
    }

Above code will find list of files which has name a.
I used 4 extensions here to test(.jpg,.mp3,.mp4,.txt).If you need more just add them in boolean accept() method.

EDIT :
Here is the most simplified version of what OP wants.

public static void filelist()
    {
        File folder = new File("C:/");
        File[] listOfFiles = folder.listFiles();

    for (File file : listOfFiles)
    {
        if (file.isFile())
        {
            String[] filename = file.getName().split("\\.(?=[^\\.]+$)"); //split filename from it's extension
            if(filename[0].equalsIgnoreCase("a")) //matching defined filename
                System.out.println("File exist: "+filename[0]+"."+filename[1]); // match occures.Apply any condition what you need
        }
     }
}

Output:

File exist: a.jpg   //These files are in my C drive
File exist: a.png
File exist: a.rtf
File exist: a.txt
File exist: a.mp3
File exist: a.mp4

This code checks all the files of a path.It will split all filenames from their extensions.And last of all when a match occurs with defined filename then it will print that filename.

ridoy
  • 6,274
  • 2
  • 29
  • 60
  • @bowmore, i changed the code and it works perfectly now,so can you re-consider your downvote? – ridoy Jul 17 '13 at 11:21
  • @user2511713, inform me if this is what you want. – ridoy Jul 17 '13 at 11:33
  • I would slightly modify the `accept` method to improve the performance: `public boolean accept(final File dir, final String name) { if (name.charAt(0) != 'a') { return false; if (name.endsWith(".jpg")||name.endsWith(".txt")||name.endsWith(".mp3")||name.endsWith(".mp4")) { return true; } return false;}` – agad Jul 17 '13 at 12:32
  • Your code will now work for .jpg,.mp3,.mp4,.txt .I want it to work with any file extension no matter what.have a look at my answer – user2511713 Jul 17 '13 at 12:49
  • But you not mentioned that earlier in your question,u mentioned only 3 formats there.So make sure about what you want before asking a question and clearly mention that. – ridoy Jul 17 '13 at 13:44
3

If you're looking for any file with name "a" regardless of the suffix, the glob that you're looking for is a{,.*}. The glob is the type of regular expression language used by shells and the Java API to match filenames. Since Java 7, Java has support for globs.

This Glob explained

  • {} introduces an alternative. The alternatives are separated with ,. Examples:
    • {foo,bar} matches the filenames foo and bar.
    • foo{1,2,3} matches the filenames foo1, foo2 and foo3.
    • foo{,bar} matches the filenames foo and foobar - an alternative can be empty.
    • foo{,.txt} matches the filenames foo and foo.txt.
  • * stands for any number of characters of any kind, including zero characters. Examples:
    • f* matches the filenames f, fa, faa, fb, fbb, fab, foo.txt - every file that's name starts with f.
  • The combination is possible. a{,.*} is the alternatives a and a.*, so it matches the filename a as well as every filename that starts with a., like a.txt.

A Java program that lists all files in the current directory which have "a" as their name regardless of the suffix looks like this:

import java.io.*;
import java.nio.file.*;
public class FileMatch {
    public static void main(final String... args) throws IOException {
        try (final DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."), "a{,.*}")) {
            for (final Path entry : stream) {
                System.out.println(entry);
            }
        }
    }
}

or with Java 8:

import java.io.*;
import java.nio.file.*;
public class FileMatch {
    public static void main(final String... args) throws IOException {
        try (final DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."), "a{,.*}")) {
            stream.forEach(System.out::println);
        }
    }
}

If you have the filename in a variable and you want to see whether it matches the given glob, you can use the FileSystem.getPathMatcher() method to obtain a PathMatcher that matches the glob, like this:

final FileSystem fileSystem = FileSystems.getDefault();
final PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:a{,.*}");
final boolean matches = pathMatcher.matches(new File("a.txt").toPath());
Christian Hujer
  • 17,035
  • 5
  • 40
  • 47
0

You can try some thing like this

File folder = new File("D:\\DestFile");
File[] listOfFiles = folder.listFiles();

for (File file : listOfFiles) {
if (file.isFile()) {
    System.out.println("found ."+file.getName().substring(file.getName().lastIndexOf('.')+1));
}
}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

Try this:

        File parentDirToSearchIn = new File("D:\\DestFile");
        String fileNameToSearch = "a";
        if (parentDirToSearchIn != null && parentDirToSearchIn.isDirectory()) {
            String[] childFileNames = parentDirToSearchIn.list();
            for (int i = 0; i < childFileNames.length; i++) {
                String childFileName = childFileNames[i];
                //Get actual file name i.e without any extensions..
                final int lastIndexOfDot = childFileName.lastIndexOf(".");
                if(lastIndexOfDot>0){
                    childFileName = childFileName.substring(0,lastIndexOfDot );
                    if(fileNameToSearch.equalsIgnoreCase(childFileName)){
                        System.out.println(childFileName);
                    }
                }//otherwise it could be a directory or file without any extension!
            }
        }
Chandan Adiga
  • 576
  • 4
  • 14
0

You could make use of the SE 7 DirectoryStream class :

public List<File> scan(File file) throws IOException {
    Path path = file.toPath();
    try (DirectoryStream<Path> paths = Files.newDirectoryStream(path.getParent(), new FileNameFilter(path))) {
        return collectFilesWithName(paths);
    }
}

private List<File> collectFilesWithName(DirectoryStream<Path>paths) {
    List<File> results = new ArrayList<>();
    for (Path candidate : paths) {
        results.add(candidate.toFile());
    }
    return results;
}

private class FileNameFilter implements DirectoryStream.Filter<Path> {
    final String fileName;

    public FileNameFilter(Path path) {
        fileName = path.getFileName().toString();
    }

    @Override
    public boolean accept(Path entry) throws IOException {
        return Files.isRegularFile(entry) && fileName.equals(fileNameWithoutExtension(entry));
    }

    private String fileNameWithoutExtension(Path candidate) {
        String name = candidate.getFileName().toString();
        int extensionIndex = name.lastIndexOf('.');
        return extensionIndex < 0 ? name : name.substring(0, extensionIndex);
    }

}

This will return files with any extension, or even without extension, as long as the base file name matches the given File, and is in the same directory.

The FileNameFilter class makes the stream return only the matches you're interested in.

bowmore
  • 10,842
  • 1
  • 35
  • 43
0
public static boolean everExisted() {
    File directory=new File(your directory location);//here /home/user/desktop/sound/
            final String name=yourFileName;  //here a;
                    String[] myFiles = directory.list(new FilenameFilter() {
                        public boolean accept(File directory, String fileName) {
                            if(fileName.lastIndexOf(".")==-1) return false;
                            if((fileName.substring(0, fileName.lastIndexOf("."))).equals(name))
                                return true;
                            else return false;
                        }
                    });
           if(myFiles.length()>0)
               return true;
        }
}

When it returns, it will stop the method.

Silvr Swrd
  • 59
  • 1
  • 1
  • 4
-2

Try this one

FileLocationWithExtension = "nameofFile"+ ".*"
ridoy
  • 6,274
  • 2
  • 29
  • 60