두 개의 등록 정보 파일 (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를 사용하여 원하는 것을 얻을 수있었습니다.
** ** 루프 내에 파일 객체'새 파일 (pathToFile)'을 만들지 마십시오 **. 루프 외부에서 한 번만 생성하고 참조를 전달하십시오. – Braj
'java.util.Properties'를 사용하지 않는 이유는 무엇입니까? – Jens
@Braj : 예, 실제로는 루프 외부에서 생성되었습니다. 그것은 복사/붙여 넣기에 대한 나의 실수였습니다. – DaeYoung