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

时间:2014-08-21 09:02:30

标签: java file input path

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

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

1 个答案:

答案 0 :(得分: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");
}