简体   繁体   中英

Getting the file path from file name in java

To get the file path from file name in directory I have src/test/resources/datasheets directory.

src/test/resources/datasheets
xyz/a1.txt
abc/b1/txt

It has many directories again

I need to get the file path If i give the file name ex : "a1.txt" I need to get as src/test/resources/datasheets/xyz/a1.txt

Thanks in advance

Just write a recursive method to check all sub directories. I hope that will work:

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 "";
    }
}

This information is easily accessible if you had referred to the [ File docs ].

File myDir = File(String pathname);
if(myDir.isDirectory()) {
    File[] contents = myDir.listFiles(); 
}

See what your contents[] looks like and make necessary modifications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM