有 Java 编程相关的问题?

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

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

我想确定是否使用java将新文件或文档放置在特定的文件夹/目录中。例如,“C:\Users\User\Documents”目录中没有任何文件,然后我从Internet下载了一个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编程新手:)*)


共 (2) 个答案

  1. # 1 楼答案

    谢谢你们的提示!:)我通过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);
            }
        }
    }
    

    希望这能帮助其他人。也要感谢那些帮助我的人,以及创造这本书的不同研究材料的作者:)这本书要归功于克里谢尔先生:)

  2. # 2 楼答案

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

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