자바에서 이미 있는 파일에 텍스트 추가하려고 하는데요

조회수 4570회

자바에서 이미 있는 파일에 텍스트를 추가하려고 하는데요 어떻게하면되죠?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    Java 7

    Files 클래스 쓰면 쉬워요.

    try {
        Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
    }catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    

    근데 님이 똑같은 파일에 여러번 쓰면 파일 열고 닫고 많이해서 느리니까

    try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)))) {
        out.println("the text");
        //more code
        out.println("more text");
        //more code
    }catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    

    이렇게 하세요.

    FileWriter의 두번째 인자는 파일에 추가할건지 여부를 말하고요. 여러번 쓸거면 BufferedWriter를 추천합니다. PrintWriterprintln에 접근권한을 주는데 이건 님이 많이써본 System.out.그거랑 똑같아요.

    자바 옛날 버전에선

    try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true))); out.println("the text"); out.close(); } catch (IOException e) { //exception handling left as an exercise for the reader }

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)