我需要比较具有不同扩展名的文件名,以查找具有相同名称的文件。我不关心扩展名。我正在使用SimpleFileVisitor方法visitFile()来浏览文件。我只是使用根目录名或目录名并使用walkFileTree()来获取文件,所以我不知道文件的数量。该进程必须是后台进程。我曾考虑过使用线程走路通过文件并匹配它们,但没有获得实现方法。那么如何添加比较方案呢?我获取文件名的代码是:-

package trigger;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class ProcessFilePath extends SimpleFileVisitor<Path>{

        String [] str;
        String name;

        @Override
        public FileVisitResult visitFile(Path aFile, BasicFileAttributes aAttrs) throws IOException

        {
            str= aFile.toFile().getName().split("\\.");
             name=str[0];
             System.out.println("filename : " + name);
             return FileVisitResult.CONTINUE;

        }



    }

最佳答案

从路径获取文件名。

File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());


用于删除文件扩展名

str.substring(0, str.lastIndexOf('.'));


比较文件名。

// These two have the same value
new String("test").equals("test") ==> true

// ... but they are not the same object
new String("test") == "test" ==> false

// ... neither are these
new String("test") == new String("test") ==> false

// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" ==> true

// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st"  ==> true

// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false

10-07 19:12
查看更多