有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何等待以某个字符开头的文件列表被创建

    File dir = new File(dirName);
    ArrayList<File> files = new ArrayList<File>();
    dir.listFiles(new FileFilter()
    {

        @Override
        public boolean accept(File file)
        {
            if (!file.isFile()){
                return false;
            }

            String name = file.getName();

            if (!StringUtils.startsWith(name, startsWith)){
                return false;
            }

            if (!StringUtils.endsWith(name, ensWith)){
                return false;
            }

            files.add(file);
            s_logs.log(Level.INFO, "File that startswith " + startsWith + " found ");
            return true;

        }
    });

这段代码用于获取所有以字符开头的文件,但我想等到文件创建完毕。 你能建议一条路吗


共 (1) 个答案

  1. # 1 楼答案

    您可以使用名为WatchService的东西,它在Java中的新java.nio.file包中提供

    您可以使用此命令查看任何文件创建的目录。如果需要,还可以递归地检查目录。Oracle还提供了一个代码示例,您可以使用它开始使用

    https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java

    您需要修改上述示例中的processEvents()方法,并检查child对象是否以您试图查找的字符开头

    希望这能帮助你开始