[java] Get the filePath from Filename using Java

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

This question is related to java file filepath

The answer is


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.


You can use the Path api:

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

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

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

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"

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...


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to filepath

Anaconda / Python: Change Anaconda Prompt User Path How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax? How do I get the file name from a String containing the Absolute file path? Get the filePath from Filename using Java Directory.GetFiles: how to get only filename, not full path? Getting current directory in .NET web application Extract a part of the filepath (a directory) in Python Check whether a path is valid in Python without creating a file at the path's target How to get the file path from URI? File path issues in R using Windows ("Hex digits in character string" error)