16

Is there a easy way to get the filePath provided I know the Filename?

2
  • You mean you have the name of a file and want to get the path? What about if there are many files named like this? Commented Nov 22, 2012 at 9:49
  • yes. i wanted to know if there is any oneliner code which will get the path of a already xisting file. I think i will have to search through the directories and then list the files. Commented Nov 22, 2012 at 10:25

5 Answers 5

21

You can use the Path api:

Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
Sign up to request clarification or add additional context in comments.

1 Comment

i am still using java version "1.6.0_31". I suppose Path api comes with Java 1.7
18

Look at the methods in the java.io.File class:

File file = new File("yourfileName");
String path = file.getAbsolutePath();

2 Comments

i already have a file name 'file1.txt' and is stored in D:\\IM\\EclipseWorkspaces\\runtime-EclipseApplication\\Proj\\Software and If a do File file = new File("file1.txt"); and get the file.getAbsolutePath, it gives me D:\\IM\\EclipseVersions\\EclipseSDK3_7\\file1.txt. which is not i want.
like you said in your comment under the post: you can't avoid traversing directories.
8

I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:

System.out.println("File path: " + new File("Your file name").getAbsolutePath());

The File class has several more methods you might find useful.

Comments

8

Correct solution with "File" class to get the directory - the "path" of the file:

String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();

which will return:

path = "C:\\Temp\\your directory"

2 Comments

getParent() returns a String. Would need to change File path to String path
You can use getParentFile()
0

You may use:

FileSystems.getDefault().getPath(new String()).toAbsolutePath();

or

FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()

This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.

Example: /src/main/java...

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.