Is there a easy way to get the filePath provided I know the Filename?
-
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?m0skit0– m0skit02012-11-22 09:49:16 +00:00Commented 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.user1688404– user16884042012-11-22 10:25:00 +00:00Commented Nov 22, 2012 at 10:25
Add a comment
|
5 Answers
You can use the Path api:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
1 Comment
user1688404
i am still using java version "1.6.0_31". I suppose Path api comes with Java 1.7
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
2 Comments
user1688404
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.
jlordo
like you said in your comment under the post: you can't avoid traversing directories.
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
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
Ascalonian
getParent() returns a String. Would need to change
File path to String pathloggeek
You can use getParentFile()
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...