【问题标题】:New file inside a directory using java使用java的目录中的新文件
【发布时间】:2015-12-22 19:04:52
【问题描述】:

我想确定一个新文件或文档是否放置在使用 java 的特定文件夹/目录中。例如,“C:\Users\User\Documents”目录下没有文件,然后我从网上下载了一个pdf文件并放在上述目录中。如何使用 java 编程语言确定是否在目录中检测到新文件? (它还应该打印出目录名和新文件名)。我可以对如何使用 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 编程新手 :) *)

【问题讨论】:

标签: java file directory


【解决方案1】:

您可以使用Watch Service。监视注册对象的更改和事件的监视服务。例如,文件管理器可以使用监视服务来监视目录的更改,以便在创建或删除文件时更新其文件列表的显示。 一个很好的例子可以找到here

您也可以使用来自 Apache Foundation 的 Commons IO 库,主要是 org.apache.commons.io.monitor 包。

【讨论】:

  • 谢谢! :) 这对我形成程序有很大帮助:)
【解决方案2】:

谢谢你们的提示! :) 我发现了如何使用 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);
        }
    }
}

希望这可以帮助其他人。还要感谢那些帮助过我的人以及用于创建这个的不同研究材料的作者 :) 感谢 Mr.Kriechel 为这个 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2010-10-15
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    相关资源
    最近更新 更多