Is there a easy way to get the filePath provided I know the Filename?
Get the filePath from Filename using Java
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
You can use the Path
api:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
i am still using java version "1.6.0_31". I suppose Path api comes with Java 1.7 –
Questionnaire
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
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
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.
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"
getParent() returns a String. Would need to change
File path
to String path
–
Dunkin You can use getParentFile() –
Vorticella
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...
© 2022 - 2024 — McMap. All rights reserved.