2014-01-31 4 views
1

Примечание: Пожалуйста, простите меня, если у меня есть ошибка на английском языке.NullPointerException при загрузке данных в объект java.util.Properties

Я изучаю java! и теперь я пытаюсь загрузить свойства из файла в объект java.util.Properties ... , но у меня есть исключение. Я получаю filenamegetClass().getResource("path/to/resource").toFile() и создаю из него объект File; затем прочитайте содержимое. но когда я отправляю InputStream файла на «загрузку» метода, получите NullPointerException.

Это мой код:

final class Main 
{ 
    protected Properties config; 

    protected Properties getConfig() 
    { 
     if(this.config == null) 
     { 
      String filename = this.getClass().getResource("/tiny.properties").getFile(); 
      System.out.print( filename+ "\n"); 
      File f = new File(filename); 

      try(InputStream propsFile = new FileInputStream(f)) 
      { 
       int ch = 0; 
       while((ch = propsFile.read()) != -1) 
       { 
        System.out.print((char) ch); // I can get ALL content of File Here 
       } 
       this.config.load(propsFile); // But here I got NullPointerException! 
      } 
      catch(IOException exc) 
      { 
       assert true : "Can't read properties file!"; 
      } 
     } 
     return this.config; 
    } 
} 

и Мое исключение:

Exception in thread "main" java.lang.NullPointerException 
    at ir.teanlab.japp1.mavenproject1.Main.getConfig(Main.java:43) // this.config.load(...) 
    at ir.teanlab.japp1.mavenproject1.Main.getSqlConnection(Main.java:57) 
    at ir.teanlab.japp1.mavenproject1.Main.<init>(Main.java:67) 
    at ir.teanlab.japp1.mavenproject1.App.main(App.java:15) 
+0

http://viralpatel.net/blogs/loading-java-properties-files/ Может быть проблема с вашим файловым путем – Reddy

ответ

3

Вы получаете NullPointerException, потому что config по-прежнему равен нулю, когда вы вызываете метод load. Вы должны инициализировать config объект так:

config = new Properties();

Вероятно, лучше всего, чтобы поставить его прямо под чекой нулевой для него:

if(this.config == null) 
{ 
    config = new Properties(); 
    .... 
1

Вы только что создали ссылку в этой строке Properties config;, но не создали объект

Создание объекта например Properties config=new Properties()

0

Попробовать удалить, если условие (если (this.config == null)). Окончательный код:

final class Main 
{ 
    protected Properties config; 

    protected Properties getConfig() 
    { 

     this.config=new new Properties(); 
      String filename =this.getClass().getResource("/tiny.properties").getFile(); 
      System.out.print( filename+ "\n"); 
      File f = new File(filename); 

      try(InputStream propsFile = new FileInputStream(f)) 
      { 
       int ch = 0; 
       while((ch = propsFile.read()) != -1) 
       { 
        System.out.print((char) ch); // I can get ALL content of File Here 
       } 
       this.config.load(propsFile); // But here I got NullPointerException! 
      } 
      catch(IOException exc) 
      { 
       assert true : "Can't read properties file!"; 
      } 

     return this.config; 
    } 
} 
0

Проблема заключается в том, что ваша config переменная не инициализирована и, следовательно, по-прежнему нулевой. Поэтому в вашем блоке try/catch вы должны добавить config = new Properties();

На боковой ноте есть более простой способ получить InputStream. Мы используем следующую технику (Java 6):

InputStream inputStream = null; 
    Properties config = null; 
    try 
    { 
     config = new Properties(); 
     inputStream = this.getClass().getClassLoader().getResourceAsStream("path + resource name"); 
     if (inputStream != null) 
     { 
      config.load(inputStream); 
     } 
     else 
     { 
      throw new FileNotFoundException("property file '" + "path + resource name" + "' not found in the classpath"); 
     } 
    } 
    catch (IOException e) 
    { 
     throw new RuntimeException(e); 
    } 
    finally 
    { 
     if (inputStream != null) 
     { 
      try 
      { 
       inputStream.close(); 
      } 
      catch (IOException e) 
      { 
       throw new RuntimeException(e); 
      } 
     } 
    } 

Очевидно, что с помощью java 7 вы можете попробовать с ресурсами.

Смежные вопросы