简体   繁体   English

如何从 java 中的源根目录获取文件的路径?

[英]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.我在src文件夹下的 java 中有一个文件,我想在运行时获取它相对于源文件夹的路径。 For example-例如-

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

I would like to have the result packageOne/SomeFile.java .我想要结果packageOne/SomeFile.java I couldn't find a way, I tried getPath() , getAbsoultePath() and every similar method.我找不到方法,我尝试了getPath()getAbsoultePath()和所有类似的方法。

You want to construct a relative path.你想构造一个相对路径。 AFAIK there is no ready function to use. AFAIK 没有现成的 function 可供使用。

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...假设您有一个祖先节点 (src) 并且您有 SomeFile.java,以下代码可能有效,但我没有尝试...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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