简体   繁体   中英

How to get the path of the file from source root in java?

I have a file in java under the src folder, I want to get its path at runtime relative to the source folder. For example-

myProject
  -- src
    -- packageOne
      -- SomeFile.java

I would like to have the result packageOne/SomeFile.java . I couldn't find a way, I tried getPath() , getAbsoultePath() and every similar method.

You want to construct a relative path. AFAIK there is no ready function to use.

Given that you have one of the ancestor nodes (src) and you have SomeFile.java, the following code might work but I did not try...

File src = new File("...");
File somefile = new File("...");

String relpath = somefile.getName();
File cursor = somefile.getParentFile();
while (!cursor.getAbsolutePath().equals(src.getAbsolutePath()) {
  somefile = cursor.getName() + File.pathSeparator + somefile;
}
System.out.println("relative path: "+relpath);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM