簡體   English   中英

如何知道resourceBoundle加載的屬性的絕對路徑

[英]How to know absolute path to a properties loaded by resourceBoundle

我正在使用以下代碼加載屬性:

ResourceBoundle boundle = ResourceBundle.getBundle("file")

我想知道加載文件的絕對路徑。 例如,如果我在tomcat的webapps文件夾中的Web應用程序中執行此代碼,我想獲取:

c:\tomcat8\webapps\example\WEB-INF\classes\file.properties.

我怎么知道這條路?

我已經通過這篇文章“獲取當前工作目錄”解決了我的問題。 對於我的問題,我只需要這個,一旦我知道工作目錄,我就可以找到絕對路徑

public class Test {
public static void main(String... args) throws Exception {
    URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
    System.out.println(location.getFile());
}}

我想也許這個解決方案並不能涵蓋所有情況,但這對我來說已經足夠了。

你無法從獲得的物理位置ResourceBundle ,但如果你知道這是用來加載它的路徑,那么你就可以找出物理位置。 像這樣:

String resourceToLoad = "file";
URL url = this.getClassLoader().getResource(resourceToLoad);
ResourceBoundle bundle = ResourceBundle.getBundle(resourceToLoad);

url將具有資源的物理位置 - 至少在大多數情況下。

請記住, ResourceBundle也可以由Java類支持,而不是像屬性文件那樣。 ClassLoader.getResource不理解ResourceBundle和Java類之間的映射。 如果您希望能夠支持這些,您必須實現類似於ResourceBundle所做的算法,以便搜索與其方案匹配的類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM