Get the filePath from Filename using Java
Asked Answered
Q

5

16

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

Questionnaire answered 22/11, 2012 at 9:47 Comment(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?Obstruct
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.Questionnaire
I
21

You can use the Path api:

Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
Insatiable answered 22/11, 2012 at 9:49 Comment(1)
i am still using java version "1.6.0_31". I suppose Path api comes with Java 1.7Questionnaire
S
18

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

File file = new File("yourfileName");
String path = file.getAbsolutePath();
Scudo answered 22/11, 2012 at 9:49 Comment(2)
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.Questionnaire
like you said in your comment under the post: you can't avoid traversing directories.Scudo
B
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.

Bencher answered 22/11, 2012 at 9:51 Comment(0)
G
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"
Gert answered 13/7, 2018 at 5:11 Comment(2)
getParent() returns a String. Would need to change File path to String pathDunkin
You can use getParentFile()Vorticella
M
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...

Muscovado answered 27/1, 2020 at 16:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.