2012-03-28 3 views
0

I WebSphere를 사용하는 자바 EE이 오류 메시지가 있어요 :내 속성 파일을로드하는 방법?

Exception reading propertiesfile in init java.lang.NullPointerException 
java.lang.NullPointerException 
    at java.io.Reader.<init>(Reader.java(Inlined Compiled Code)) 
    at java.io.InputStreamReader.<init>(InputStreamReader.java(Inlined Compiled Code)) 
    at java.util.Properties.load(Properties.java(Compiled Code)) 
    at se.prv.register.admin.util.MessageHandler.loadDictionary(MessageHandler.java:90) 
    at se.prv.register.admin.util.MessageHandler.<clinit>(MessageHandler.java:15) 

이 내 메시지가 같은 디렉토리에 messages.properties 파일 넣었습니다

package se.prv.pandora.arendeprocess.util; 

import java.io.InputStream; 
import java.util.Properties; 

import org.apache.log4j.Logger; 

public class MessageHandler extends AbstractTextHandler{ 
    private static Properties dictionary; 
    private final static String dictionaryFileName="messages.properties"; 
    private final static String className="se.prv.pandora.arendeprocess.util.MessageHandler"; 
    private static Logger logger = Logger.getLogger(MessageHandler.class); 

    static { 
     loadDictionary(); 
    } 

    public static void main(String[] args) { 
     String str = getParameterizedMessageTest("TEST",new String[]{"PETER","GÖRAN"}); 
     System.out.println(str); 
    } 
    public static String getMessage(String key){ 
     return getMessage(key,true); 
    } 
    public static String getMessage(String key,boolean useReference){ 
     logger.debug("!!!! getMessage "+ key); 
     if (key==null || key.length()==0){ 
      throw new RuntimeException("GetMessage without key"); 
     } 
     if (dictionary==null){ 
      loadDictionary(); 
     } 
     if (useReference){ 
      return getFullMessage(getMessage(dictionary,key)); 
     } 
     else { 
      //String str = getMessage(dictionary,key); 
      //logger.debug(str); 
      String str2 = getCoreMessage(getMessage(dictionary,key)); 
      //logger.debug(str2); 
      return str2; 
     } 
    } 
    public static String getFirstPartOfMessage(String key){ 
     if (key==null || key.length()==0){ 
      throw new RuntimeException("GetMessage without key"); 
     } 
     if (dictionary==null){ 
      loadDictionary(); 
     } 
     String msg = getMessage(dictionary,key); 
     int pos = msg.indexOf('$'); 
     if (pos==-1){ 
      return msg; 
     } 
     else { 
      return msg.substring(0,pos); 
     } 
    } 
    public static String getLastPartOfMessage(String key){ 
     if (key==null || key.length()==0){ 
      throw new RuntimeException("GetMessage without key"); 
     } 
     if (dictionary==null){ 
      loadDictionary(); 
     } 
     String msg = getMessage(dictionary,key); 
     int pos = msg.lastIndexOf('$'); 
     if (pos==-1){ 
      return msg; 
     } 
     else { 
      return msg.substring(pos+1); 
     } 
    } 
    public static String getParameterizedMessage(String key, String [] params){ 
     if (dictionary==null){ 
      loadDictionary(); 
     } 
     return getParameterizedMessage(dictionary,key,params); 
    } 
    private static void loadDictionary(){  
     String fileName = getPropertiesPath()+dictionaryFileName; 
     //String fileName = "se/prv/register/admin/dao/sql-map-config.xml"; 

     try { 
      dictionary=new Properties(); 
      //InputStream fileInput = Class.forName("se.prv.register.admin.util.MessageHandler").getClassLoader().getResourceAsStream(fileName); 
      InputStream fileInput = Class.forName(className).getClassLoader().getResourceAsStream(fileName); 
      dictionary.load(fileInput); 
      fileInput.close(); 
     } 
     catch(Exception e) { 
      System.err.println("Exception reading propertiesfile in init "+e); 
      e.printStackTrace(); 
      dictionary=null; 
     } 
    } 
    private static String getCoreMessage(String str){ 
     StringBuffer buff = new StringBuffer(); 
     boolean doCopy=true; 
     for (int i=0;i<str.length();i++){ 
      if (str.charAt(i)=='$'){ 
       doCopy=!doCopy; 
       continue; 
      } 
      if (doCopy){ 
       buff.append(str.charAt(i)); 
      } 
     } 
     return buff.toString(); 
    } 
    private static String getFullMessage(String str){ 
     int pos = str.indexOf('$'); 
     if (pos==-1){ 
      return str; 
     } 
     StringBuffer buff = new StringBuffer(str); 

     int originalLength = buff.length(); 
     for (int i=pos+1;i<buff.length();i++){ 
      if (buff.charAt(i)== '$'){ 
       String key = buff.substring(pos+1,i).trim(); 
       String msg = getMessage(dictionary,key); 
       buff.replace(pos,i+1,msg); 
       if (buff.length()!=originalLength){ 
        i += (buff.length()-originalLength); 
        originalLength=buff.length(); 
       } 
       pos = buff.indexOf("$",i+1); 
       if (pos==-1){ 
        break; 
       } 
       else { 
        i = pos+1; 
       } 
      } 
     } 
     return buff.toString(); 
    } 
// private static void loadDictionary(){  
//  loadDictionary(dictionary,dictionaryFileName,className); 
// } 
} 

package se.prv.register.admin.util; 

import java.io.FileInputStream; 
import java.io.InputStream; 
import java.util.Properties; 

import org.apache.log4j.Logger; 

import se.prv.framework.general.PRVWebSphere; 
import se.prv.framework.util.Strings; 

public abstract class AbstractTextHandler { 

     private static final String propertiesPath="//se//prv//register//properties//"; 
     protected static Logger logger = Logger.getLogger(AbstractTextHandler.class); 

//  static { 
//   loadProperties(); 
//  } 
     protected static String getPropertiesPath(){ 
      return propertiesPath; 
     } 
     protected static String getMessage(Properties dictionary,String key){ 
      if (dictionary==null){ 
       return "ERROR"; 
      } 
      String msg = dictionary.getProperty(key); 
      //System.out.println("KEY="+key); 
      if (msg==null){ 
       return "?!Meddelande " +key + " saknas!?"; 
      } 
      return msg; 
     } 
     protected static String getParameterizedMessage(Properties dictionary,String key,String []params){ 
      if (dictionary==null){ 
       return "ERROR"; 
      } 
      String msg = dictionary.getProperty(key); 
      if (msg==null){ 
       return "?!Meddelande " +key + " saknas!?"; 
      } 
      if (params==null){ 
       return msg; 
      } 
      StringBuffer buff = new StringBuffer(msg); 
      for (int i=0;i<params.length;i++){ 
       String placeHolder = "<<"+(i+1)+">>"; 
       if (buff.indexOf(placeHolder)!=-1){ 
        replace(buff,placeHolder,params[i]); 
       } 
       else { 
        remove(buff,placeHolder); 
       } 
      } 
      return buff.toString(); 
     } 
     public static String getParameterizedMessageTest(String key,String []params){ 
      String msg = "HEJ <<1>>!HUR MÅR DU? HEJ DÅ FRÅN <<2>>"; 
      if (msg==null){ 
       return "?!Meddelande saknas!?"; 
      } 
      if (params==null){ 
       return msg; 
      } 
      StringBuffer buff = new StringBuffer(msg); 
      for (int i=0;i<params.length;i++){ 
       String placeHolder = "<<"+(i+1)+">>"; 
       if (buff.indexOf(placeHolder)!=-1){ 
        replace(buff,placeHolder,params[i]); 
       } 
       else { 
        remove(buff,placeHolder); 
       } 
      } 
      return buff.toString(); 
     } 
     private static void replace(StringBuffer buff,String placeHolder,String param){ 
      int pos = buff.indexOf(placeHolder); 
      if (pos==-1){ 
       return; 
      } 
      buff.replace(pos,pos+placeHolder.length(),param); 
     } 
     private static void remove(StringBuffer buff,String placeHolder){ 
      int pos = buff.indexOf(placeHolder); 
      if (pos==-1){ 
       return; 
      } 
      buff.replace(pos,pos+placeHolder.length(),placeHolder); 
     } 
     protected static void loadDictionary(Properties dictionary,String fileName,String className){  
      //String fileName = "se/prv/register/admin/dao/sql-map-config.xml"; 

      try { 
       dictionary=new Properties(); 
       InputStream fileInput = Class.forName("se.prv.register.admin.util.AbstractTextHandler").getClassLoader().getResourceAsStream(fileName); 
       dictionary.load(fileInput); 
       fileInput.close(); 
      } 
      catch(Exception e) { 
       logger.error("Exception reading propertiesfile in init "+e); 
       e.printStackTrace(); 
       dictionary=null; 
      } 
     } 
    } 

내 코드입니다 log4j.properties 파일을 작성해야합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

답변

1

예외는 Properties.load()의 깊이에서 발생한 널 포인터 예외입니다. 그 이유는 전달 된 매개 변수 (fileInput)가 null이기 때문입니다. fileName에 지정된 경로가 잘못 되었기 때문에 가능성이 큽니다.

경로 앞에 /을 추가하십시오.

또한 파일이 존재하는지 확인하십시오. getResourceAsStream() 메소드는 클래스와 관련된 리소스에서 파일을 찾습니다 (예 : 프로그램을 실행하면 .jar 파일의 일부 여야합니다).

+0

Eclipse 기반의 IBM RAd 내부에서 프로그램을 실행합니다. 디스크에서 속성 파일을로드하려고 시도하지만 파일 이름이 실제 파일을 가리키는지를 검사 할 때에도 여전히 예외가 발생합니다. –

+1

디스크에서 파일을로드하려는 경우 'dictionary.load'를 사용하여 Reader (예 : FileReader)를 전달해야합니다. 'getResourceAsStream()'메소드는 자원 내의 경로를 찾는다. '/'를 사용하여 경로를 앞에 넣으려고 했습니까? 질문에 인용 된 코드에는 경로가'/'로 시작하지 않는다는 인상을주는 주석이 있습니다. 이 경우 경로는 클래스 위치와 관련하여 해석됩니다. [cont.] – Attila

+1

[cont] 예 : 클래스가 "se/prv/register/admin/dao /"폴더에 있고 리소스 경로를 "se/prv/register/admin/dao/sql-map-config.xml"으로 지정하면 클래스 로더는 "se/prv/register/admin/dao/se/prv/register/admin/dao/sql-map-config.xml"에서 파일을 찾으십시오 (디렉토리 계층 구조의 중복에주의하십시오). 경로를 "/se/prv/register/admin/dao/sql-map-config.xml"로 지정하면 로더는 "se/prv/register/admin/dao/sql-map"에서 파일을 찾습니다. -config.xml " – Attila

2

당신은 속성은 클래스 패스 리소스가 아닌 파일 시스템에서 파일로 파일을로드해야합니다 감사합니다. 이것을 수행하는 방법에 대한이 기사를 읽으십시오. Smartly load your properties. 대신 아래의 일을

+0

예 ResourceBundle을 사용해야한다고 생각하지만이 코드는 개발 과정에서 개발되어 다른 프로젝트에서 가져온 것으로이 프로젝트와 같은 속성을 사용해야한다고 말했습니다. 그래서 파일을 사용할 수있게 만들고 ResourceBundle 사용으로 변경하는 것을 고려하고 있지만, 예를 들어 Enumeration이 사용되고 semem과 같은 proeprties를로드하도록 반복하는 것에 회의적입니다. 그것은 추상의 최고 수준이 아닙니다. 감사합니다. –

1

,

InputStream fileInput = Class.forName(className).getClassLoader().getResourceAsStream(fileName); 

이 작업을 수행 :

InputStream fileInput = MessageHandler.class.getClassLoader().getResourceAsStream(fileName); 
+0

감사하지만 속성 파일을로드 할 때 여전히 예외가 발생합니다. –

+1

'propertiesPath'가 잘못되었습니다. 'se/prv/register/properties'로 변경하고 작동하는지 확인하십시오. 'log4j.properties'가있는 곳입니까? – adarshr

+0

propertiesPath를 비어있는 것으로 설정하고 파일 이름 만 사용하고 클래스와 동일한 디렉토리에 특성 파일을 배치하십시오. 필자는 log4j 등록 정보 파일과 동일한 디렉토리에보다 편리한 위치에 등록 정보 파일을두기를 원했습니다.이 파일은 WAS 서버가 아닌 독립 실행 파일이므로이 파일을 실행하고 있기 때문에 선택하지 않았습니다. 테스트 할 클래스.) –

1

라인 InputStream fileInput = Class.forName(className).getClassLoader().getResourceAsStream(fileName);

반환 null.

NPE가 독자에게 던져지는 이유입니다.

왜 입력 스트림이 null입니까? fileName에 잘못된 값이 포함되어 있기 때문입니다. 그래서 디버그해라. 라인

String fileName = getPropertiesPath()+dictionaryFileName;

하고 반환 무엇을 볼 수있는 토글 중단 점.

+0

fileName을 디버깅하여 나에게 잘 보일 것입니다 :'filename : // se // prv // register // properties // messages.properties' 그 파일이 존재합니다. –

관련 문제