有 Java 编程相关的问题?

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

Java:自动检测输入文件路径

我需要创建一个从文件中获取输入的程序。为了自动找到当前路径,然后搜索输入文件,我需要使用什么

示例:我将主文件放在C:/*pathname*/中,输入文件名为INPUT.txt。如何使程序自动找到C:/*pathname*/INPUT.txt路径以获取其输入


共 (1) 个答案

  1. # 1 楼答案

    在这种情况下,可以使用递归来查找文件。通过检查当前文件是否与给定文件名匹配,可以在当前/给定目录中启动搜索过程。如果你找到一个目录,你可以在这个目录中继续递归搜索过程

    private static final File findFile(final String rootFilePath, final String fileToBeFound) {
    
        File rootFile = new File(rootFilePath);
        File[] subFiles = rootFile.listFiles();
        for (File file : subFiles != null ? subFiles : new File[] {}) {
            if (file.getAbsolutePath().endsWith(fileToBeFound)) {
                return file;
            } else if (file.isDirectory()) {
                File f = findFile(file.getAbsolutePath(), fileToBeFound);
                if (f != null) {
                    return f;
                }
            }
        }
    
        return null; // null returned in case your file is not found
    
    }
    
    public static void main(final String[] args){
    
         File fileToBeFound = findFile("C:\\", "INPUT.txt"); // search for the file in all the C drive
         System.out.println(fileToBeFound != null ? fileToBeFound.getAbsolutePath() : "Not found");
    
         //you can also use your current workspace directory, if you're sure the file is there
        fileToBeFound = findFile(new File(".").getAbsolutePath() , "INPUT.txt");
        System.out.println(fileToBeFound != null ? fileToBeFound.getAbsolutePath() : "Not found");
    }