使用Java在目录中创建新文件

3
我希望你能够用Java编程语言来检测特定文件夹/目录中是否有新的文件或文档,并使其输出目录名称和新文件名。例如,"C:\Users\User\Documents" 目录中没有任何文件,然后我从互联网上下载了一个PDF文件并将其放置在该目录中。如何使用Java编程语言确定是否在该目录中检测到新文件?您能否给我一些关于如何创建这种程序的提示?它应该是连续的或无限循环的。我尝试使用以下代码实现:
package readfilesfromfolder;
import java.io.File;


public class ReadFilesFromFolder {

public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
  static String temp = "";

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
    listFilesForFolder(folder);
  }

  public static void listFilesForFolder(final File folder) {

    for (final File fileEntry : folder.listFiles()) {
      if (fileEntry.isDirectory()) {

        listFilesForFolder(fileEntry);
      } else {
        if (fileEntry.isFile()) {
          temp = fileEntry.getName();
          if ((temp.substring(temp.lastIndexOf('.') + 1,        temp.length()).toLowerCase()).equals("txt"))
            System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
        }

      }
    }
  }
}

但根据结果,它只访问了目录,没有列出任何新项目。此外,它还没有进入循环,因为我还没有放置它。谢谢 :)(*注意:我还是Java编程的新手 :) *)


2
请查看此链接:https://dev59.com/Um445IYBdhLWcg3wR4VO - cylon
2
使用 WatchService:https://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html - Ramanlfc
哦,谢谢 :) 我会阅读并学习它的。 :) - JustOnce
2个回答

2
您可以使用Watch Service。它是一个监视已注册对象的更改和事件的监视服务。例如,文件管理器可以使用监视服务来监视目录的更改,以便在创建或删除文件时更新文件列表的显示。
您可以在这里找到一个很好的例子。
您还可以使用Apache基金会的Commons IO库,主要使用org.apache.commons.io.monitor包。

谢谢! :) 那将帮助我很多来形成程序 :) - JustOnce

0

感谢大家的提示! :) 我通过使用 WatchService 找到了如何做到这一点 :)

这是基于我的研究和阅读得出的输出结果 :)

 public static void main(String[] args) throws IOException{
    // TODO code application logic here
    WatchService watchService = FileSystems.getDefault().newWatchService();
    //The path needed for changes
    Path directory = Paths.get("C:\\Users\\User\\Documents");
    //To determine whether a file is created, deleted or modified
    //ENTRY_CREATE can be changed to ENTRY_MODIFY and ENTRY_DELETE
    WatchKey watchKey = directory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
    //This portion is for the output of what file is created, modified, or deleted
    while (true){ 
        for (WatchEvent<?> event : watchKey.pollEvents()) {
            System.out.println(event.kind());
            Path file = directory.resolve((Path) event.context());
            System.out.println(file);
        }
    }
}

希望这能帮助其他人。同时感谢那些帮助过我的人以及创造这个项目所使用的不同研究材料的作者们 :) 特别感谢Kriechel先生 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接