【问题标题】:How to detect if a file(with any extension) exist in java如何检测java中是否存在文件(带有任何扩展名)
【发布时间】:2013-07-17 10:42:57
【问题描述】:

我正在文件夹中搜索声音文件,想知道声音文件是否存在,可能是 .mp3、.mp4 等。我只是想确保文件名(不带扩展名)存在。

例如文件搜索 /home/user/desktop/sound/a

如果存在 a.mp3 或 a.mp4 或 a.txt 等,则返回找到。

我试过了:

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");
}

缺点:即使找到了我在问题中从未想过的文件,它也会继续搜索。欢迎提出任何建议

【问题讨论】:

  • 如果文件存在,我可以成功得出结论,但我必须提供扩展名
  • 您使用的是 Java 6 还是 Java 7?
  • 我已经编辑了我迄今为止尝试过的内容
  • 这可能会有所帮助(我最近发布的答案)stackoverflow.com/questions/17652826/…。更改匹配标准,然后检查数组大小。
  • java -version on ubuntu 终端提供 java 版本 "1.7.0_21" Java(TM) SE Runtime Environment (build 1.7.0_21-b11) Java HotSpot(TM) 64-Bit Server VM (build 23.21) -b01,混合模式)

标签: java file file-io


【解决方案1】:

这段代码可以解决问题..

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

此代码检查路径的所有文件。它将所有文件名与其扩展名分开。最后,当与定义的文件名匹配时,它将打印该文件名

【讨论】:

  • @bowmore,我更改了代码,现在可以完美运行,所以你能重新考虑你的否决吗?
  • @user2511713,如果这是你想要的,请告诉我。
  • 我会稍微修改accept方法以提高性能: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;}
  • 您的代码现在适用于 .jpg,.mp3,.mp4,.txt 。无论如何,我希望它适用于任何文件扩展名。看看我的答案
  • 但是您在前面的问题中没有提到这一点,您在那里只提到了 3 种格式。所以在提出问题之前请确定您想要什么并明确提及。
【解决方案2】:

如果您要查找名称为 "a" 的任何文件(无论后缀如何),您要查找的 globa{,.*}glob 是 shell 和 Java API 用来匹配文件名的正则表达式语言类型。从 Java 7 开始,Java 支持 glob。

这个Glob解释了

  • {} 介绍了另一种选择。备选方案用, 分隔。例子:
    • {foo,bar} 匹配文件名 foobar
    • foo{1,2,3} 匹配文件名 foo1foo2foo3
    • foo{,bar} 匹配文件名 foofoobar - 替代可以为空。
    • foo{,.txt} 匹配文件名 foofoo.txt
  • * 代表任意数量的任意类型的字符,包括零个字符。例子:
    • f* 匹配文件名 ffafaafbfbbfabfoo.txt - 每个文件名都以 f 开头。
  • 可以组合。 a{,.*}aa.* 的替代品,因此它匹配文件名a 以及每个以a. 开头的文件名,例如a.txt

一个列出当前目录中所有以"a" 为名称的文件(无论后缀如何)的Java 程序如下所示:

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);
            }
        }
    }
}

或使用 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);
        }
    }
}

如果变量中有文件名,并且想查看它是否与给定的 glob 匹配,可以使用FileSystem.getPathMatcher() 方法获取与 glob 匹配的PathMatcher,如下所示:

final FileSystem fileSystem = FileSystems.getDefault();
final PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:a{,.*}");
final boolean matches = pathMatcher.matches(new File("a.txt").toPath());

【讨论】:

    【解决方案3】:

    你可以试试这样的

    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));
    }
    }
    

    【讨论】:

    • 更好:java.io.File.list(FilenameFilter); if (listOfFiles.length > 0) {System.out.println("found");}
    • “a”其实就是这里的文件名。文件夹里面有很多文件(1000左右)。用这个方法好不好?
    • @agad:FilenameFilter is "/home/user/desktop/sound/a" here?
    • @user2511713 你可以这样做
    【解决方案4】:

    试试这个:

            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!
                }
            }
    

    【讨论】:

      【解决方案5】:

      您可以使用 SE 7 DirectoryStream 类:

      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);
          }
      
      }
      

      这将返回具有任何扩展名的文件,甚至没有扩展名,只要基本文件名与给定的文件匹配,并且位于同一目录中。

      FileNameFilter 类使流只返回您感兴趣的匹配项。

      【讨论】:

        【解决方案6】:
        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;
                }
        }
        

        当它返回时,它会停止该方法。

        【讨论】:

          【解决方案7】:

          试试这个

          FileLocationWithExtension = "nameofFile"+ ".*"
          

          【讨论】:

          • 试试看,为什么?这如何回答这个问题?
          • @ridoy 我不知道它在 java 中是如何工作的,但星号会返回可以在目录中找到的任何名称和任何扩展名
          • 不适用于 java.io.File 它没有。显然你还没有尝试过。 -1
          • @EJP:确实如此。如果 /home/user/desktop/sound/a.* 可用,其中 * 代表任何类型,我确实想返回 true。
          • @user2511713 下定决心。要么它不起作用,要么它回答了这个问题。不能同时进行。
          猜你喜欢
          • 2017-12-20
          • 2011-07-08
          • 1970-01-01
          • 2011-01-14
          • 2020-05-10
          • 2013-05-03
          • 2012-01-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多