Nishikanta Sahoo
Nishikanta Sahoo

Reputation: 1

How to find absolute path from a relative path in file system

A java class ReadFile1 in the TestA Project. And another class TestRead in project TestB. I want to read that class ReadFile1 in TestRead class. I have the only relative path, then how can i read that.

Example

My class is present in D:\EIX-New-Source\source\message-kernel\src\main\java\com\eix\transform\parser\MessageTransformer.java

message-kernel is the project in source folder.

and I am doing the test in D:\EIX-New-Source\source\msg-Test\src\com\coreJava\rnd\RelativePath.java

when I run this program then I got the result as D:\EIX-New-Source\source\message-kernel\target\classes

But I am expecting the result should be D:\EIX-New-Source\source\message-kernel\src\main\java\com\eix\transform\parser\MessageTransformer.java

Upvotes: 0

Views: 4280

Answers (3)

Shreyos Adikari
Shreyos Adikari

Reputation: 12754

Firstly, Java save any file relative to the current working directory.If you give a package declaration then it will create the folder accordingly inside the current directory.
If you always want files to be saved relative to the location of the Java files and not the current working directory, you need to find that directory and pretend it to get an absolute path.

The working directory is where you run the program from i.e. where you call java TestClass, so when you want to write files relative to the class that's executing you'll have to know the current directory and append the relative path from there e.g.

public class TestClass {
  public void printFullPath() {
        String fullPath = String.format("%s/%s", System.getProperty("user.dir"),   this.getClass().getPackage().getName().replace(".", "/"));
        System.out.println(fullPath);
    }

}

For more details visit How to use relative path instead of absolute path?

Upvotes: 0

HemChe
HemChe

Reputation: 2337

Try the below method for getting the absolute path of your class file and then you can append the remaining path from relative file path to get the actual absolute path of your file.

String getAbsolutePath(){
java.security.ProtectionDomain pd =
YourClassName.class.getProtectionDomain();
if ( pd == null ) return null;
java.security.CodeSource cs = pd.getCodeSource();
if ( cs == null ) return null;
java.net.URL url = cs.getLocation();
if ( url == null ) return null;
java.io.File f = new File( url.getFile() );
if (f == null) return null;

return f.getAbsolutePath();
}

Upvotes: 1

Bhushan Bhangale
Bhushan Bhangale

Reputation: 10987

You did not mention what you want to do after reading the file. You can read the file by create a input stream. The input stream works for relative path also.

FileInputStream inputStream = new FileInputStream(new File("../../com/eix/cromics/tdlr/ReadFile1"));

If you want to use it as java api then you need to define the dependency of project TestB on TestA.

Upvotes: 0

Related Questions