How to detect if a file(with any extension) exist in java
file, file-io, java
Solution
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.
Problem
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