gpt4 book ai didi

java - java中根据文件名获取文件路径

转载 作者:行者123 更新时间:2023-12-01 10:11:36 24 4
gpt4 key购买 nike

从目录中的文件名获取文件路径我有 src/test/resources/datasheets 目录。

src/test/resources/datasheetsxyz/a1.txtabc/b1/txt

它又有很多目录

如果我给出文件名,我需要获取文件路径例如:“a1.txt”我需要获取为src/test/resources/datasheets/xyz/a1.txt

提前致谢

最佳答案

只需编写一个递归方法来检查所有子目录即可。我希望这会起作用:

import java.io.File;

public class PathFinder {

public static void main(String[] args) {
String path = getPath("a1.txt", "src/test/resources/datasheets");
System.out.println(path);
}

public static String getPath(String fileName, String folder) {
File directory = new File(folder);

File[] fileList = directory.listFiles();
for (File file : fileList) {
if (file.isFile()) {
if(fileName.equals(file.getName())) {
return file.getAbsolutePath();
}
} else if (file.isDirectory()) {
String path = getPath(fileName, file.getAbsolutePath());
if(!path.isEmpty()) {
return path;
}
}
}

return "";
}
}

关于java - java中根据文件名获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36094611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com