0

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

3
  • Can you show us the code you are using so we can see where you might be having difficulty? How to create a Minimal, Complete, and Verifiable example Commented Mar 18, 2016 at 21:35
  • Isn't abc/b1/txt supposed to be abc/b1.txt? Commented Mar 18, 2016 at 21:39
  • Are you running tests from something like maven, which defines a directory for test resources as src/test/resources? If so, when running your tests, the resources would get copied into the build directory, and the path to the a1.txt resource would actually only be datasheets/xyz/a1.txt Commented Mar 18, 2016 at 21:44

2 Answers 2

1

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 "";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.