【问题标题】:Not able to move .txt files to archive folder in java [duplicate]无法将.txt文件移动到java中的存档文件夹[重复]
【发布时间】:2019-08-15 19:48:35
【问题描述】:

我需要将所有以 .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 应该移动到存档文件夹

【问题讨论】:

  • 你文件夹里的文件叫什么名字?
  • 您看过 Path.endsWith(String) 上的 Javadoc 了吗?我会引用:On UNIX for example, the path"foo/bar" ends with "foo/bar" and "bar". It does not end with "r" or "/bar" - 因此whatever.txt 不会“以”.txt 结尾。

标签: java


【解决方案1】:

这里是doc about 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 转换为String 并调用String.endsWith(String) 而不是Path.endsWith(String)

【讨论】:

    【解决方案2】:

    你可以用这个:

    String extension = "";
    
    int i = fileName.lastIndexOf('.');
    if (i > 0) {
        extension = fileName.substring(i+1);
    }
    

    假设您正在处理类似 Windows 的简单文件名,而不是 archive.tar.gz 之类的文件名。

    顺便说一句,对于目录可能有'.',但文件名本身没有(如/path/to.a/file)的情况,你可以这样做

    String extension = "";
    
    int i = fileName.lastIndexOf('.');
    int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
    
    if (i > p) {
        extension = fileName.substring(i+1);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2014-06-12
      • 2016-07-02
      相关资源
      最近更新 更多