开发者

How can I get relative path of the folders in my android project?

开发者 https://www.devze.com 2022-12-27 18:03 出处:网络
How can I get the relative path of the folders in my project using code? I\'ve created a new folder i开发者_如何学编程n my project and I want its relative path so no matter where the app is, the path

How can I get the relative path of the folders in my project using code?

I've created a new folder i开发者_如何学编程n my project and I want its relative path so no matter where the app is, the path will be correct.

I'm trying to do it in my class which extends android.app.Activity.

Perhaps something similar to "get file path from asset".


Make use of the classpath.

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


Are you looking for the root folder of the application? Then I would use

 String path = getClass().getClassLoader().getResource(".").getPath();

to actually "find out where I am".


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


With this I found my project path:

new File("").getAbsolutePath();

this return "c:\Projects\SampleProject"


You can check this sample code to understand how you can access the relative path using the java sample code

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

Here getPath will display the relative path of the file.


In Android, application-level meta data is accessed through the Context reference, which an activity is a descendant of.

For example, you can get the source directory via the getApplicationInfo().sourceDir property. There are methods for other folders as well (assets directory, data dir, database dir, etc.).


Generally we want to add images, txt, doc and etc files inside our Java project and specific folder such as /images. I found in search that in JAVA, we can get path from Root to folder which we specify as,

String myStorageFolder= "/images"; // this is folder name in where I want to store files.

String getImageFolderPath= request.getServletContext().getRealPath(myStorageFolder);

Here, request is object of HttpServletRequest. It will get the whole path from Root to /images folder. You will get output like,

C:\Users\STARK\Workspaces\MyEclipse.metadata.me_tcat7\webapps\JavaProject\images


With System.getProperty("user.dir") you get the "Base of non-absolute paths" look at

Java Library Description

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号