如何在我的android项目中获取文件夹的相对路径?

Ale*_*ian 32 java eclipse resources android

如何使用代码获取项目中文件夹的相对路径?

我在我的项目中创建了一个新文件夹,我想要它的相对路径,所以无论应用程序在哪里,路径都是正确的.

我正努力在我的班级中进行扩展android.app.Activity.

也许类似于"从资产中获取文件路径".

Bal*_*usC 24

利用类路径.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("path/to/folder");
File file = new File(url.toURI());
// ...
Run Code Online (Sandbox Code Playgroud)

  • 它与类路径根相关.你前面不需要`c:/ absolute/path/to/java/program`.试试以上.打印`url`或`file`的结果.玩它,你会明白的. (5认同)
  • 如果通过"path/to/folder"你的意思是我需要插入项目文件夹的路径,那么它的重点是什么? (3认同)
  • 难道不是因为您不了解类路径是什么吗? (2认同)

Ken*_*net 19

您在寻找应用程序的根文件夹吗?然后我会用

 String path = getClass().getClassLoader().getResource(".").getPath();
Run Code Online (Sandbox Code Playgroud)

实际上"找出我在哪里".


Zin*_*tet 6

File relativeFile = new File(getClass().getResource("/icons/forIcon.png").toURI());
myJFrame.setIconImage(tk.getImage(relativeFile.getAbsolutePath()));
Run Code Online (Sandbox Code Playgroud)