[英]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.