2014-10-04 2 views
0

Jtextfield의 입력을 테스트 속성 설정 파일에 추가하려고합니다. 그러나 텍스트를 추가하려고 할 때마다 NullPointerException이 발생합니다. Properties API가 추가/제거/편집을 허용하지 않기 때문에 BufferedWriter도 시도했지만 작동하지 않는다는 것을 읽었습니다. 누구든지이 일을 할 수있는 방법을 알고 있다면 나는 매우 감사 할 것입니다. JButton를 통해JTextField to Properties 파일

덧붙이 텍스트 :

if (userField.getText().toString().equals("")) { 
       lblNullUser.setVisible(true); 
      } else { 
       lblNullUser.setVisible(false); 
      } 

      if(!chckbxRememberUser.isSelected()) { 
       //To do: go to Lynx 
      } else { 
       String user = userField.getText(); 
       c.prop.setProperty("user", user); //null on this line; problem might be the key but not sure how to fix 

       try { 

        c.prop.store(c.outputSteam, null); 
       } catch (IOException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } 
      } 
     } 

구성 클래스 : 키 또는 값이 null의 경우

public String Config() throws IOException{ 
    String result = ""; 
    prop = new Properties(); 
    propFileName = "config.properties"; 

    inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); 
    outputSteam = new FileOutputStream("config.properties"); 
    prop.load(inputStream); 
    if (inputStream == null) { 
     throw new FileNotFoundException("Config file '" + propFileName + "' not found."); 
    } 

    //Date time = new Date(System.currentTimeMillis()); 

    return result; 
} 
+0

'c.prop '이 나오는 코드를 표시하십시오. –

답변

0

HashtableProperties의 부모 클래스입니다 NullPointerException가 발생합니다.

키와 값이 모두 null이 아닌지 확인하십시오. 귀하의 경우 value이 null이거나 properties 개체 자체가 null입니다. 다음과 같은 체크를 추가하여 속성의 유효성을 검사하고 업데이트하십시오.

String user = userField.getText(); 
if (user != null && c.prop != null) { 
    c.prop.setProperty("user", user); 
} else { 
    // Some params are null - log and verify 
} 
0

NullPointer 예외를 피하려면 속성을로드하기 전에 inputStream에서 null을 확인하는 것이 좋습니다.

if (inputStream == null) { 
    throw new FileNotFoundException("Config file '" + propFileName + "' not found."); 
} 
prop.load(inputStream); 

그러나, 전체 코드는 문제가 훨씬 더 가능성이 포함되어

  • 이 구성은() 생성자를 될 운명인가? 그것은 String을 반환하기 때문이 아닙니다. 그런 식으로 인스턴스 변수를 초기화하는 것은 의미가 없습니다.
  • 어디서나 inputStream 및 outputStream을 닫지 않습니다.
  • 미리 (필요하기 전에) outputStream을 여는 것은 좋지 않은 생각입니다.
  • getter가없는 다른 클래스의 필드에 직접 액세스하면 스타일이 잘못됩니다.
  • ...