2016-08-14 2 views
0

config.properties에 새 등록 정보를 추가하려고합니다. 이 일을 할 수있는 방법이 있습니까?null 인 경우 등록 정보 파일에 등록 정보 추가

나의 현재 설정 클래스는 다음과 같습니다

package com.template; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.util.Properties; 

public class Config { 

    static File folder = new File(System.getProperty("user.home") + "/Documents/Electrocode Productions/template"); 

    public static void add() { 
     if(!folder.exists()) { 
      try { 
       folder.mkdirs(); 
      } catch(SecurityException e) { 
       Log.error(e); 
      } 
     } 

     Properties config = new Properties(); 
     OutputStream output = null; 
     Path filePath = Paths.get(folder + "/config.properties");  
     if(!(filePath == null)) { 
      try { 
       output = new FileOutputStream(folder + "/config.properties"); 

       config.setProperty("log", "true"); 

       config.store(output, null); 
      } catch(IOException e) { 
       Log.error(e); 
      } finally { 
       if(output !=null) { 
        try { 
         output.close(); 
        } catch(IOException e) { 
         Log.error(e); 
        } 
       } 
      } 
     } 
    } 

    public static String get(String value) { 
     Properties config = new Properties(); 
     InputStream input = null; 

     try { 
      input = new FileInputStream(folder + "/config.properties"); 

      config.load(input); 
     } catch(IOException e) { 
      Log.error(e); 
     } finally { 
      if (input != null) { 
       try { 
        input.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     return config.getProperty(value).trim(); 
    } 
} 

당신이 그것을 편집하는 경우이 파일을 덮어하지 않으므로이, 노력하고 있습니다,하지만 당신은 항목을 삭제하면, 당신은 완전히 전체를 삭제해야 파일을 사용하여 해당 항목을 다시 추가하십시오.

내 궁극적 인 목표는 프로그램을 닫고 설정 파일을 수정 한 다음 새 인수로 설정 파일을 다시 열 수 있도록하는 것이지만 인수를 삭제하면 의존하기 때문에 프로그램에 충돌하지 않습니다 설정 파일의 응답에. (나는 그것이 의미가 있기를 바랍니다. 그것은 기본적으로 대부분의 비디오 게임과 같습니다).

+0

이것은 매우 명확하지 않습니다. 설명하기 위해 [최소 테스트 케이스] (http://stackoverflow.com/help/mcve)를 만들 수 있습니까? –

+0

@Oliver는 문제가 "null을 반환 할 수 없다"는 것을 알았습니다. 나는 그것을 "돌아 오는"unknow "로 변경해야했다;" " .equals (null) 대신 get (value) .equals ("unknow")를 사용하십시오. 도와 줘서 고마워! – BudSkywalker

답변

0

속성을 사용하기 전에 속성에서 얻은 값의 유효성을 검사해야합니다. 예 : 당신은 여기에 없었던 값 .trim()을 할 수 없습니다.

public class Config { 

    static final File folder = new File(System.getProperty("user.home") + "/Documents/Electrocode Productions/template"); 
    static final File file = new File(folder, "config.properties"); 

    public static void add() throws IOException { 
     if (file.exists()) 
      return; 

     // create directories as needed. 
     folder.mkdirs(); 

     Properties config = new Properties(); 
     config.setProperty("log", "true"); 

     try (OutputStream out = new FileOutputStream(file)) { 
      config.store(out, null); 
     } 
    } 

    public static String get(String key, String defaultValue) { 
     if (!file.exists()) 
      return defaultValue; 

     try (InputStream in = new FileInputStream(file)) { 
      Properties config = new Properties(); 

      config.load(input); 
     } catch(IOException e) { 
      Log.error(e); 
      return defaultValue; 
     } 

     String value = config.getProperty(key); 
     if (value == null) 
      return defaultValue; 
     value = value.trim(); 
     if (value.isEmpty()) 
      return defaultValue; 
     return value; 
    } 
} 
+0

이 코드를 이용해 주셔서 감사합니다! 나는 그 문제가 "null을 돌려 줄 수 없다"는 것을 발견했다. 나는 그것을 "돌아 오는"unknow "로 변경해야했다;" " .equals (null) 대신 get (value) .equals ("unknow")를 사용하십시오. 다시 한번 당신을 도와주세요. – BudSkywalker

+0

@BudSkywalker 여기가 기본값을 사용하는 것이 가장 좋습니다. 알 수없는 경우 원하는 값을 전달할 수 있습니다. Btw 당신은 null을 사용할 수 있지만 비교는'if (value == null)'이어야합니다. –