如何检测java中是否存在文件(具有任何扩展名)
我正在文件夹中搜索声音文件,想知道声音文件是否存在,可能是.mp3、.mp4等。我只想确保文件名(不带扩展名)存在 例如,文件搜索/home/user/desktop/sound/a 如果存在a.mp3、a.mp4或a.txt等,则返回find 我试过这个:如何检测java中是否存在文件(具有任何扩展名),java,file,file-io,Java,File,File Io,我正在文件夹中搜索声音文件,想知道声音文件是否存在,可能是.mp3、.mp4等。我只想确保文件名(不带扩展名)存在 例如,文件搜索/home/user/desktop/sound/a 如果存在a.mp3、a.mp4或a.txt等,则返回find 我试过这个: File f=new File(fileLocationWithExtension); if(f.exist()) return true; else return false; 但是这里我必须通过扩展,否则它总是返回false
File f=new File(fileLocationWithExtension);
if(f.exist())
return true;
else return false;
但是这里我必须通过扩展,否则它总是返回false
对任何来这里的人来说,这是我发现的最好的方法
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");
}
缺点:即使找到了我在问题中从未想过的文件,它仍将继续搜索。欢迎任何建议您可以尝试类似的方法
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));
}
}
试试这个
FileLocationWithExtension = "nameofFile"+ ".*"
这段代码将实现这一目的
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"))));
}
}
上述代码将查找名为a的文件列表我在这里使用了4个扩展来测试(.jpg、.mp3、.mp4、.txt)。如果需要更多扩展,只需将它们添加到
boolean accept()
方法中即可
编辑:这是OP想要的最简单的版本
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
}
}
}
输出:
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
此代码检查路径中的所有文件。它将从扩展名中拆分所有文件名。最后,当与定义的文件名匹配时,它将打印该文件名尝试以下操作:
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!
}
}
File parentDirToSearchIn=新文件(“D:\\DestFile”);
字符串fileNameToSearch=“a”;
if(parentDirToSearchIn!=null&&parentDirToSearchIn.isDirectory()){
字符串[]childfilename=parentDirToSearchIn.list();
对于(int i=0;i0){
childFileName=childFileName.substring(0,lastIndexOfDot);
if(filename到search.equalsIgnoreCase(childFileName)){
System.out.println(childFileName);
}
}//否则它可能是一个没有任何扩展名的目录或文件!
}
}
您可以使用SE 7类:
公共列表扫描(文件)引发IOException{
路径路径=file.toPath();
try(DirectoryStream path=Files.newDirectoryStream(path.getParent(),newfilenamefilter(path))){
返回collectFilesWithName(路径);
}
}
私有列表CollectFileWithName(目录流路径){
列表结果=新建ArrayList();
用于(路径候选:路径){
results.add(candidate.toFile());
}
返回结果;
}
私有类FileNameFilter实现DirectoryStream.Filter{
最终字符串文件名;
公共文件名筛选器(路径){
fileName=path.getFileName().toString();
}
@凌驾
公共布尔接受(路径项)引发IOException{
返回Files.isRegularFile(entry)和&fileName.equals(fileNameWithoutExtension(entry));
}
不带OutExtension的私有字符串文件名(候选路径){
字符串名称=候选者.getFileName().toString();
int extensionIndex=name.lastIndexOf('.');
返回extensionIndex<0?name:name.substring(0,extensionIndex);
}
}
这将返回具有任何扩展名的文件,甚至不带扩展名的文件,只要基本文件名与给定文件匹配,并且位于同一目录中
FileNameFilter类使流只返回您感兴趣的匹配项
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;
}
}
当它返回时,它将停止该方法。如果您要查找任何名为
“a”
的文件,而不管后缀是什么,那么您要查找的glob是a{,.*}
。glob是shell和javaapi用于匹配文件名的正则表达式语言类型。自Java7以来,Java就支持globs
这个地球仪解释道
引入了一种替代方案。备选方案用{}
分隔。示例:,
匹配文件名{foo,bar}
和foo
bar
匹配文件名foo{1,2,3}
、foo1
和foo2
foo3
匹配文件名foo{,bar}
和foo
-可选项可以为空foobar
匹配文件名foo{.txt}
和foo
foo.txt
表示任何种类的任意数量的字符,包括零个字符。示例:*
匹配文件名f*
,f
,fa
,faa
,fb
,fbb
,fab
——每个文件名都以foo.txt
开头f
- 这种结合是可能的
是a{,.*}
和a
的替代项,因此它匹配文件名a.*
,以及以a
开头的每个文件名,如a.
a.txt
“A”
,而不考虑后缀,如下所示:
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);
}
}
}
}
final FileSystem fileSystem = FileSystems.getDefault();
final PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:a{,.*}");
final boolean matches = pathMatcher.matches(new File("a.txt").toPath());
如果文件存在,我能够成功地得出结论,但我必须提供扩展。您是否使用Java 6或Java 7?我已经用我尝试过的内容进行了编辑,这可能会有所帮助(我最近发布了一个答案)。更改匹配的标准,然后检查数组大小。java-ubuntu终端上的版本提供java版本“1.7.0_21”java(TM)SE运行时环境(构建1.7.0_21-b11)java热点(TM)64位服务器VM(构建23.21-b01,混合模式)更好:java.io.File.list(FilenameFilter);如果(listOfFiles.length>0){System.out.println(“find”);}“a”实际上是此处的文件名。该文件夹包含许多文件(大约1000个)。使用此方法是否明智?@agad:FilenameFilter为“/ho”
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);
}
}
}
final FileSystem fileSystem = FileSystems.getDefault();
final PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:a{,.*}");
final boolean matches = pathMatcher.matches(new File("a.txt").toPath());