Get the filePath from Filename using Java - java

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

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();

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"

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

Related

How to get path to package in Eclipse (Java)

I'm currently reading a txt file in Java, which is located in a package with the scanner object.
To receive the file location I use a quick and dirty method:
File currentDirectory = new File(new File(".").getAbsolutePath());
String location = currentDirectory.getAbsolutePath().replace(".", "")+"\\corefiles\\src\\filereadingexample\\";
Is there a better way of doing so?
I'd love to improve my code.
Greetings
J
Use a URL
URL resource = getClass().getResource("/path/to/text/file.txt");
As the path, since your text file is inside a package, use the package structure. For example, assume your file(myfile.txt) is inside
com.myproject.files
package, your path should be
"/com/myproject/files/myfile.txt"
(mind the leading slash. It's necessary)
Now you can create a File using the URL
new File(resource.getFile());
The "resource.getFile()" returns the absolute path to the file also.
Hope this helps
Get current diretory path
String currentDirPath = System.getProperty("user.dir");
String ohterPackages = currentDirPath + File.separator + "filereadingexample\\fileName.txt";
User home directory
String homePath = System.getProperty("user.home");

Get path directory only and discard file in Java

How do we actually discard last file from java string and just get the file path directory?
Random Path input by user:
C:/my folder/tree/apple.exe
Desired output:
C:/my folder/tree/
closest solution i found is from here . The answer from this forum only display last string acquired not the rest of it. I want to display the rest of the string.
The easiest and most failsafe (read: cross-platform) solution is to create a File object from the path.
Like this:
File myFile = new File( "C:/my folder/tree/apple.exe" );
// Now get the path
String myDir = myFile.getParent();
Try that:
String path = "C:/my folder/tree/apple.exe";
path = path.substring(0, path.lastIndexOf("/")+1);

How to get absolute path to file in /resources folder of your project

Assume standard maven setup.
Say in your resources folder you have a file abc.
In Java, how can I get absolute path to the file please?
The proper way that actually works:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.
(The seemingly obvious new File(resource.getPath()) doesn't work for all paths! The path is still URL-encoded!)
You can use ClassLoader.getResource method to get the correct resource.
URL res = getClass().getClassLoader().getResource("abc.txt");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();
OR
Although this may not work all the time, a simpler solution -
You can create a File object and use getAbsolutePath method:
File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();
You need to specifie path started from /
URL resource = YourClass.class.getResource("/abc");
Paths.get(resource.toURI()).toFile();
Create the classLoader instance of the class you need, then you can access the files or resources easily.
now you access path using getPath() method of that class.
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("chromedriver.exe").getPath();
System.out.println(path);
There are two problems on our way to the absolute path:
The placement found will be not where the source files lie, but
where the class is saved. And the resource folder almost surely will lie somewhere in
the source folder of the project.
The same functions for retrieving the resource work differently if the class runs in a plugin or in a package directly in the workspace.
The following code will give us all useful paths:
URL localPackage = this.getClass().getResource("");
URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
String localDir = localPackage.getPath();
String loaderDir = urlLoader.getPath();
System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);
Here both functions that can be used for localization of the resource folder are researched. As for class, it can be got in either way, statically or dynamically.
If the project is not in the plugin, the code if run in JUnit, will print:
loaderDir = /C:.../ws/source.dir/target/test-classes/
localDir = /C:.../ws/source.dir/target/test-classes/package/
So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName), for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.
If the class is in the package that is in the plugin, the output of the same test will be:
loaderDir = /C:.../ws/plugin/bin/
localDir = /C:.../ws/plugin/bin/package/
So, again we should go up and down the folder tree.
The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:
loaderDir = /C:.../ws/plugin/
localDir = /package/
Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src or src/test/resource here.
You can insert the code into yours and see the paths that you have.
To return a file or filepath
URL resource = YourClass.class.getResource("abc");
File file = Paths.get(resource.toURI()).toFile(); // return a file
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath(); // return file path

Finding absolute path

I am looking at code new FileInputStream("config.properties").
I have the same file "config.properties" in multiple places in my project(doing windows file search) and I am now confused as to which one does this function call refer to. How do i get to know the absolute path of file?
I found this on the internet but this location doesnt look like the right answer.
"ClassName".class.getProtectionDomain().getCodeSource().getLocation().getPath() but this doesnt look it. Can you please correct it if I am wrong
You can use File:
File f = new File("config.properties");
System.out.println(f.getAbsolutePath());
The path returned will be deduced from the current working directory.
File f = new File("config.properties");
String dirPath = file.getParentFile().getAbsolutePath()

Get the absolute path of the currently edited file in Eclipse

I'd like to write a plugin that does something with the currently edited file in Eclipse. But I'm not sure how to properly get the file's full path.
This is what I do now:
IFile file = (IFile) window.getActivePage().getActiveEditor.getEditorInput().
getAdapter(IFile.class);
Now I have an IFile object, and I can retrieve it's path:
file.getFullPath().toOSString();
However this still only gives me the path relative to the workspace. How can I get the absolute path from that?
Looks like you want IResource.getRawLocation(). That returns an IPath, which also has a makeAbsolute() method if you want to be doubly sure you've got an absolute path.
I think a more Java friendly solution would be to do use the following:
IResource.getLocation().toFile()
This takes advantage of the IPath API (the getLocation() part) and will return a java.io.File instance. Of course the other answers will probably get you to where you want to be too.
On a tangential note, I find the IDE class (org.eclipse.ui.ide.IDE) a useful utility resource when it comes to editors.
The answer that worked for me (and I tested it!) was:
// Get the currently selected file from the editor
IWorkbenchPart workbenchPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class);
if (file == null) throw new FileNotFoundException();
String path = file.getRawLocation().toOSString();
System.out.println("path: " + path);
I usually call IFile.getLocation() which returns an IPath and then call IPath.toOSString().
file.getLocation().toOSString()
IWorkspace ws = ResourcesPlugin.getWorkspace();
IProject project = ws.getRoot().getProject("*project_name*");
IPath location = new Path(editor.getTitleToolTip());
IFile file = project.getFile(location.lastSegment());
into file.getLocationURI() it's the absolute path
For me, this run ok.
IWorkspaceRoot workSpaceRoot = ResourcesPlugin.getWorkspace().getRoot();
File file = workSpaceRoot.getRawLocation().makeAbsolute().toFile();
file list from this location:
File[] files = file.listFiles();

Categories