2014-05-23 7 views
0

두 개의 등록 정보 파일 (source.properties 및 destination.properties)을 읽고 소스에서 대상으로 각 행의 키/값 쌍을 작성하는 Java로 작성된 프로그램이 있습니다. 필자는 PrintWriter 대신 FileUtils.writeStringToFile 메서드를 사용하고 Java 표준 API의 FileWriter를 사용하기로 결정했습니다. 내가 찾은 것은 소스 파일의 마지막 줄만 대상 파일에 겹쳐 쓰는 것입니다. source.properties의commons io FileUtils.writeStringToFile

내용
사용자 이름은가/
호스트 = ABC에게

static void writeToFile(Map<String,String> map, String pathToFile) {         
    Iterator<Map.Entry<String,String>> itr = map.entrySet().iterator(); 
    File path = new File(pathToFile); 
    while(itr.hasNext()) { 
     Map.Entry<String,String> pairs = (Map.Entry<String,String>)itr.next(); 
     FileUtils.writeStringToFile(path,pairs.getKey() + "=" + pairs.getValue()); 
    } 
} 

지도 키를 포함
호스트 = ABC destination.properties의

내용을 = 값 쌍을 소스 파일에서 가져옵니다. 프로그램을 디버깅 할 때 루프가 두 번 반복되고 Map에 FileUtils의 모든 올바른 데이터와 메서드가 두 번 호출되어 소스 파일의 각 데이터 행을 썼음을 알 수있었습니다.

누군가 내가 왜 앞에서 언급 한 결과물을 얻었는지 설명 할 수 있습니까?

[업데이트]
PrintWriter를 사용하여 원하는 것을 얻을 수있었습니다.

+0

** ** 루프 내에 파일 객체'새 파일 (pathToFile)'을 만들지 마십시오 **. 루프 외부에서 한 번만 생성하고 참조를 전달하십시오. – Braj

+0

'java.util.Properties'를 사용하지 않는 이유는 무엇입니까? – Jens

+0

@Braj : 예, 실제로는 루프 외부에서 생성되었습니다. 그것은 복사/붙여 넣기에 대한 나의 실수였습니다. – DaeYoung

답변

3

utils 메서드에 파일 끝에 String을 추가하고 덮어 쓰지 말라고 알리려면 true으로 설정된 부울 인수와 함께 FileUtils#writeStringToFile을 사용해야합니다.

@Deprecated 
public static void writeStringToFile(File file, 
          String data, 
          boolean append) 
          throws IOException 

그래서 코드는 다음과 같이해야한다 :

static void writeToFile(Map<String,String> map, String pathToFile) 
{         
    Iterator<Map.Entry<String,String>> itr = map.entrySet().iterator(); 
    File path = new File(pathToFile); 
    while(itr.hasNext()) { 
    Map.Entry<String,String> pairs = (Map.Entry<String,String>)itr.next(); 
    FileUtils.writeStringToFile(path, 
     pairs.getKey() + "=" + pairs.getValue(), 
     true);// append rather than overwrite 
    } 
} 

(!) 참고 :이 방법은 사용되지 않으며 당신이 메소드 서명에 지정된 Charset와 하나를 사용해야합니다.

+0

나는 본다. 이제 나는 무슨 일이 일어나고 있는지 알고있다. 고맙습니다! – DaeYoung

+0

도움이 된 것을 기쁘게 생각합니다 :) – tmarwen