簡體   English   中英

Java讀取與該類位於同一包中的屬性文件

[英]Java read Properties file that is in same package as the class

我在其中停留了將近一個小時,所以請幫助我。

我正在使用netbeans,並且在“ Sources Packages下有一個名為com.cmsv1.properties的包。 在這個包中,我有1個Java類和.properties文件。 分別稱為config.javaconfig.properties

我已經嘗試了很多從互聯網獲得的解決方案,但是沒有任何效果。 我總是得到nullPointerException

以下是我嘗試過的解決方案:

try
          {
              Properties prop = new Properties();
              InputStream is = config.class.getResourceAsStream("config.properties");
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }

另一個是:

try
          {
              Properties prop = new Properties();
              InputStream input = config.class.getClassLoader().getResourceAsStream("config.properties");
              prop.load(input);
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }

還有更多解決方案。 請告訴我該怎么做。 記住我的java類和.properties文件都在同一個包中。 提前致謝。

如果您的編譯器將屬性文件編譯到jar中,則應該可以使用:

this.getClass().getResourceAsStream("config.properties");

您的第一次嘗試幾乎完全正確:

try
{
    Properties prop = new Properties();
    InputStream is = config.class.getResourceAsStream("config.properties");
}
catch (Exception e)
{
    System.out.println("got error");
}

除了需要加載和關閉InputStream之外:

Properties prop = new Properties();
try (InputStream is = config.class.getResourceAsStream("config.properties")) {
    prop.load(is);
}

另外,您需要捕獲需要捕獲的異常:

catch (IOException e)

這是因為其他異常,尤其是未經檢查的異常(如NullPointerException),指示程序員錯誤。 您不會抓住它們,而是讓它們使程序失敗,因此您可以發現並修復它們。 隱藏它們並不能使您的程序正常運行!

始終使用日志記錄語句,異常鏈接或printStackTrace()顯示捕獲的異常的堆棧跟蹤。 如果出了什么問題,您想知道它發生的原因以及發生的位置:

catch (IOException e)
{
    e.printStackTrace();
}

關於Class.getResource和ClassLoader.getResource的使用,您應該始終使用Class.getResource(或Class.getResourceAsStream)。 原因之一是它將在Java 9模塊化應用程序中運行。

如果getResourceAsStream返回null,那是因為屬性文件與編譯的.class文件不在同一位置。

(信譽不足,無法發表評論)

你嘗試過這個嗎?

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesFile);
    properties.load(input);
public Properties getPropertiesFromFile(String propertieFileName) throws IOException
    {
        try (InputStream propertyFile = this.getClass().getClassLoader().getResourceAsStream(propertieFileName)
        {

            if (propertyFile == null)
            {
                //logger not found
            }
            Properties propeties = new Properties();
            propeties.load(propertyFile);
            return propeties;
        }
    }

暫無
暫無

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

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