[英]How can I get relative path of the folders in my android project?
如何使用代码获取项目中文件夹的相对路径?
我在我的项目中创建了一个新文件夹,我想要它的相对路径,所以无论应用程序在哪里,路径都是正确的。
我正在尝试在我的类中扩展android.app.Activity
。
也许类似于“从资产中获取文件路径” 。
利用类路径。
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("path/to/folder");
File file = new File(url.toURI());
// ...
您在寻找应用程序的根文件夹吗? 然后我会用
String path = getClass().getClassLoader().getResource(".").getPath();
实际上“找出我在哪里”。
File relativeFile = new File(getClass().getResource("/icons/forIcon.png").toURI());
myJFrame.setIconImage(tk.getImage(relativeFile.getAbsolutePath()));
有了这个,我找到了我的项目路径:
new File("").getAbsolutePath();
返回“c:\\ Projects \\ SampleProject”
您可以查看此示例代码,以了解如何使用Java示例代码访问相对路径
import java.io.File;
public class MainClass {
public static void main(String[] args) {
File relative = new File("html/javafaq/index.html");
System.out.println("relative: ");
System.out.println(relative.getName());
System.out.println(relative.getPath());
}
}
这里getPath将显示文件的相对路径。
在Android中,应用程序级元数据通过Context
引用访问,后者是一个活动的后代。
例如,您可以通过getApplicationInfo().sourceDir
属性获取源目录。 还有其他文件夹的方法(资产目录,数据目录,数据库目录等)。
通常我们希望在Java项目和特定文件夹(如/ images)中添加图像,txt,doc等文件。 我在搜索中发现,在JAVA中,我们可以获得从Root到我们指定的文件夹的路径,
String myStorageFolder= "/images"; // this is folder name in where I want to store files.
String getImageFolderPath= request.getServletContext().getRealPath(myStorageFolder);
这里,request是HttpServletRequest的对象。 它将获得从Root到/ images文件夹的整个路径。 你会得到像,
C:\\用户\\ STARK \\工作区\\ MyEclipse.metadata.me_tcat7 \\的webapps \\ JavaProject \\图片
使用System.getProperty("user.dir")
您将看到“非绝对路径的基础”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.