Get the absolute path of the currently edited file in Eclipse - java

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

Related

How to get the excel file path using java code

String dirPath = fileObj.getParentFile().getAbsolutePath();
system.out.println(dirPath);
I tried this way but its returning the Java Project Path that is Workspace path..
.getParentFile() is probably returning the parent directory, which depending on the location of your file could be the project directory. If fileObj is an object of type File, just try using fileObj.getAbsolutePath() instead.
So try this:
File fileObj = new File("myFile.xls");
String dirPath = fileObj.getAbsolutePath();
System.out.println(dirPath);
This should result in output similar to:
C:/[your project directory]/myFile.xls
JavaDoc for getParentFile():
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#getParentFile()

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 filePath from Filename using 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...

Get abs path from the currently edited file in Eclipse

I have the same problem as the guy in this post:
Get the absolute path of the currently edited file in Eclipse
but I dont understand how to do it. In the post they say that I should use IResource.getRawLocation() but how to I get the IResource from the current file that I am viewing?
IFile file2 = (IFile)workBench.getActiveWorkbenchWindow().getActivePage().getActiveEditor().getEditorInput().getAdapter(IFile.class);
IPath path = file2.getRawLocation().makeAbsolute();
String ss = path.toString();
System.out.println(ss);
But this will still not give me the right path to the linked file, I get something like:
/path/to/plugin/path/to/relative/path/to/file
An IFile is-an IResource. You don't need to get one from another. Just call file2.getRawLocation(). If that's not working it's not because it's not an IResource.
Is the file in a jar/zip/any archive file? If so, it looks like that could be the correct absolute path.

Categories