Beginner
Beginner

Reputation: 313

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

Upvotes: 0

Views: 107

Answers (2)

rdonuk
rdonuk

Reputation: 3956

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

Upvotes: 1

Debosmit Ray
Debosmit Ray

Reputation: 5403

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.

Upvotes: 0

Related Questions