Get the filePath from Filename using Java

134,229

Solution 1

You can use the Path api:

Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();

Solution 2

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

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

Solution 3

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.

Solution 4

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"
Share:
134,229
user1688404
Author by

user1688404

Updated on February 28, 2020

Comments

  • user1688404
    user1688404 about 4 years

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

  • user1688404
    user1688404 over 11 years
    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.
  • user1688404
    user1688404 over 11 years
    i am still using java version "1.6.0_31". I suppose Path api comes with Java 1.7
  • jlordo
    jlordo over 11 years
    like you said in your comment under the post: you can't avoid traversing directories.
  • Ascalonian
    Ascalonian over 5 years
    getParent() returns a String. Would need to change File path to String path