java - 如何检测文件(具有任何扩展名)是否存在于java中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17697646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:43:35  来源:igfitidea点击:

How to detect if a file(with any extension) exist in java

javafilefile-io

提问by user2511713

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.

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

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

eg.文件搜索/home/user/desktop/sound/a

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

如果存在 a.mp3 或 a.mp4 或 a.txt 等中的任何一个,则返回找到。

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

但在这里我也必须传递扩展名,否则它总是返回 false

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

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

回答by ridoy

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.

上面的代码将找到名称为a的文件列表。
我在这里使用了 4 个扩展名来测试(.jpg、.mp3、.mp4、.txt)。如果您需要更多,只需在boolean accept()方法中添加它们。

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

编辑:
这是 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
        }
     }
}

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 filenamesfrom their extensions.And last of all when a match occurs with defined filenamethen it will print that filename.

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

回答by Christian Hujer

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

如果您要查找任何带有名称的文件而"a"不管后缀如何,那么您要查找的globa{,.*}. 该水珠是由贝壳和Java API来匹配文件名使用正则表达式语言的类型。从 Java 7 开始,Java 就支持 globs。

This Globexplained

这个Glob解释了

  • {}introduces an alternative. The alternatives are separated with ,. Examples:
    • {foo,bar}matches the filenames fooand bar.
    • foo{1,2,3}matches the filenames foo1, foo2and foo3.
    • foo{,bar}matches the filenames fooand foobar- an alternative can be empty.
    • foo{,.txt}matches the filenames fooand 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 aand a.*, so it matches the filename aas well as every filename that starts with a., like a.txt.
  • {}介绍一个替代方案。选项以 分隔,。例子:
    • {foo,bar}匹配文件名foobar.
    • foo{1,2,3}匹配文件名foo1,foo2foo3.
    • foo{,bar}匹配文件名foofoobar- 替代项可以为空。
    • foo{,.txt}匹配文件名foofoo.txt.
  • *代表任意数量的任何类型的字符,包括零个字符。例子:
    • f*匹配文件名f, , fa, faa, fb, fbb, fab, foo.txt- 名称以f.
  • 组合是可能的。a{,.*}是替代项aand a.*,因此它匹配文件名a以及以 开头的每个文件名a.,例如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:

列出当前目录中所有文件名的 Java 程序,"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);
            }
        }
    }
}

or with Java 8:

或使用 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 PathMatcherthat matches the glob, like this:

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

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

回答by Ruchira Gayan Ranaweera

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

回答by Chandan Adiga

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

回答by bowmore

You could make use of the SE 7 DirectoryStreamclass :

您可以使用 SE 7DirectoryStream类:

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.

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

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

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

回答by Silvr Swrd

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.

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

回答by user2572367

Try this one

试试这个

FileLocationWithExtension = "nameofFile"+ ".*"