首页 > 解决方案 > 无法将 .txt 文件移动到 java 中的存档文件夹

问题描述

我需要将所有以 .txt 结尾的文件移动到存档文件夹。

我有以下代码,但if (sourcepath.endsWith(".txt"))不验证文件扩展名。

      File directory = new File("Archive");
      System.out.println((System.getProperty("user.dir")));
      File directory1 = new File (System.getProperty("user.dir"));
      File[] files = directory1.listFiles();
      if (! directory.exists()) {
            directory.mkdir();
            for(File f : files ) {
                   Path sourcePath = Paths.get(f.getName());
                   System.out.println(sourcePath);
                   if (sourcePath.endsWith(".txt")){   // Not validating
                       System.out.println(sourcePath.endsWith(extension));
                       Files.move(sourcePath, Paths.get("Archive"));
                   }
            }
            System.out.println("Clearing Folder.....All Files moved to Archive Directory");
      }

预期输出:

C:\Users\harsshah\workspace\FFPreBatchValidation
.classpath
.project
.settings
bin
kjnk.txt
src

kjnk.txt 应该移动到存档文件夹

标签: java

解决方案


这是关于 Path.endsWith(String)的文档

测试此路径是否以 Path 结尾,通过转换给定的路径字符串构造,完全按照 endsWith(Path) 方法指定的方式。例如,在 UNIX 上,路径“foo/bar”以“foo/bar”和“bar”结尾。它不以“r”或“/bar”结尾。请注意,不考虑尾随分隔符,因此使用字符串“bar/”在路径“foo/bar”上调用此方法会返回 true。

重要的部分是:It does not end with "r" or "/bar"

您必须将其转换Path为 aString并调用String.endsWith(String)而不是Path.endsWith(String)


推荐阅读