Apache FileUtils.writelines ()가 존재하는 경우 파일에 추가되도록 만들 수 있습니까?

StackOverflow https://stackoverflow.com/questions/1629713

문제

커먼즈 파일 꽤 멋져 보이고 파일에 추가 할 수 없다고 믿을 수 없습니다.

File file = new File(path);
FileUtils.writeLines(file, printStats(new DateTime(), headerRequired));

위의 내용은 매번 파일의 내용을 대체 하며이 코드와 마찬가지로이 내용을 계속 끝내고 싶습니다.

fw = new FileWriter(file, true);
try{
    for(String line : printStats(new DateTime(), headerRequired)){
        fw.write(line + "\n");
    }
}
finally{ 
    fw.close();
}

나는 Javadoc을 검색했지만 아무것도 찾지 못했습니다! 내가 무엇을 놓치고 있습니까?

도움이 되었습니까?

해결책

당신이 사용할 수있는 ioutils.writelines (), 두 번째 예제 에서처럼 초기화 할 수있는 작가 객체를받습니다.

다른 팁

그들은 이제 파일 루틸 클래스에서 appendstring (...)과 같은 방법입니다.

그러나 출력 스트림을 얻을 수 있습니다 fileutils.openoutputStream (...) 그리고 사용하여 글을 쓰는 것보다

write(byte[] b, int off, int len) 

파일에 apend를 제공 할 수 있도록 OFF를 계산할 수 있습니다.

편집하다

Davids 답변을 읽은 후에 나는 완충 작가가 당신을 위해이 일을 할 것임을 알고 있습니다.

BufferedWriter output = new BufferedWriter(new FileWriter(simFile));
output.append(text);

Apache FileUtils 2.1 기준 으로이 방법이 있습니다.

정적 void 쓰기 (파일 파일, 숯불 데이터, 부울 부록)

파일에 대한 오버로드가 있습니다.

public static void writeLines(File file,
          Collection<?> lines,
          boolean append)
                   throws IOException

파일 - 쓸 파일

라인 - 쓸 줄, 널 항목은 빈 줄을 생성합니다.

Append- true 인 경우 라인은 덮어 쓰기 대신 파일 끝에 추가됩니다.

CASE1 :

FileUtils.writeLine(file_to_write, "line 1");
FileUtils.writeLine(file_to_write, "line 2");

file_to_write에는 만 포함됩니다

line 2

동일한 파일에 여러 번 쓰면 파일을 덮어 씁니다.

CASE2 :

FileUtils.writeLine(file_to_write, "line 1");
FileUtils.writeLine(file_to_write, "line 2", true);

file_to_write에는 포함됩니다

line 1
line 2

두 번째 호출은 동일한 파일에 추가됩니다.

자세한 내용은 Java 공식 문서에서 확인하십시오.https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/fileutils.html#writelines(java.io.file, java.util.collection, 부울)

당신은 같은 일을 할 수 있습니다

List x = FileUtils.readLines(file);
x.add(String)
FileUtils.writelines(file,x);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top