Java,知道文件是否在文件夹中

时间:2017-10-23 15:49:24

标签: java file

大家好,我正在尝试查找特定文件是否在项目目录中。

File f = new File(System.getProperty("user.dir"));
System.out.println(f);
String archivoLiga="LigaV2";
System.out.println(f.listFiles((dir1, name) -> name.startsWith(archivoLiga) && name.endsWith(".properties")).length == 0);

但是这只有在文件处于“第一”级别时才有效,即使它在另一个文件夹中也希望它找到它。有什么想法吗?

5 个答案:

答案 0 :(得分:1)

使用Java 8的find()方法来递归子目录:

final int MAX_DEPTH = 50;  // Max depth of subdirectories to search
Path userDir = Paths.get(System.getProperty("user.dir"));
System.out.println(userDir);
String archivoLiga="LigaV2";
System.out.println(
        Files.find(
                userDir,
                maxDepth,
                (path,attr) -> path.getFileName().startsWith(archivoLiga)
                        && path.getFileName().endsWith(".properties"))
        .findAny()
        .isPresent());

答案 1 :(得分:0)

尝试递归查看子文件夹: -

public boolean checkForFile(String dirname,String prefix,String ext){

        File dir = new File(dirname);
        //System.out.println(dir);



        for(File f : dir.listFiles()){

            if(f.isFile()){
                if(f.getName().startsWith(prefix) && f.getName().endsWith(ext)){
                    System.out.println(f.getName());
                    return true;
                }
            }
            else{

                //This step starts looking inside subfolder as well 
                return checkForFile(f.getAbsolutePath(),prefix,ext);
            }

        }

        return true;
    }

答案 2 :(得分:0)

要检查文件夹中的文件,您需要使用exists()这样的java.io.File方法:

boolean exists = new File("FOLDER_PATH/FILE_NAME").exists();

if (exists) {
    System.out.println("File exists inside given folder");
} else {
    System.out.println("File does not exists inside given folder");
}

答案 3 :(得分:0)

也可以使用FileVisitor

@Getter @Setter
@RequiredArgsConstructor
public static class SearchVisitor extends SimpleFileVisitor<Path> {
    private final String fileToSearch;
    private boolean found=false;

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        if(!file.getFileName().toString().equals(fileToSearch)) return FileVisitResult.CONTINUE;
        found=true;
        return FileVisitResult.TERMINATE;
    }
}

public void test() throws IOException {
    SearchVisitor sv = new SearchVisitor("LigaV2");
    Files.walkFileTree( Paths.get(System.getProperty("user.dir")), sv);
    log.info("found file {}:{}", sv.getFileToSearch(), sv.isFound());
}

答案 4 :(得分:0)

在java文件API中使用public boolean isDirectory()以下是oracle文档的链接。测试此抽象路径名表示的文件是否为目录。

https://docs.oracle.com/javase/7/docs/api/java/io/File.html#isDirectory()