2013-03-09 1 views
2

이 프로그램은 출력 파일 이름을 묻는 메시지를 표시합니다. 텍스트 편집기 나 터미널로 출력 파일을 열려고 할 때까지. 그럼 그 파일에 아무것도 보이지 않는 것뿐입니다. 이 프로그램은 텍스트 파일을 만들지 만 파일은 비어 있습니다. 미리 도움을 주셔서 감사합니다.PrintWriter가 .txt 파일에 텍스트를 인쇄하지 않습니다.

import java.util.*; 
import java.io.IOException; 
import java.io.PrintWriter; 
/** 
* Writes a Memo file. 
* 
*/ 
public class MemoPadCreator { 
    public static void main(String args[]) { 
    Scanner console = new Scanner(System.in); 
    System.out.print("Enter Output file name: "); 
    String filename = console.nextLine(); 
    try { 
    PrintWriter out = new PrintWriter(filename); 

    boolean done = false; 
    while (!done) { 
     System.out.println("Memo topic (enter -1 to end):"); 
     String topic = console.nextLine(); 
     // Once -1 is entered, memo's will no longer be created. 
     if (topic.equals("-1")) { 
     done = true; 
    console.close(); 
     } 
     else { 
     System.out.println("Memo text:"); 
     String message = console.nextLine(); 

     /* Create the new date object and obtain a dateStamp */ 
     Date now = new Date(); 
     String dateStamp = now.toString(); 

     out.println(topic + "\n" + dateStamp + "\n" + message); 
     } 
    } 
    /* Close the output file */ 

    } catch (IOException exception) { 
    System.out.println("Error processing the file:" + exception); 
    }console.close(); 
    } 
} 

답변

5

out.flush()을 사용하여 내용을 파일로 플러시합니다.

또는 PrintWriter의 자동 세척 생성자 사용 (하지 않을 수 있습니다 을 최선의 선택을 수행) 어쨌든 옵션

입니다
public PrintWriter(Writer out,boolean autoFlush) 

의 autoflush - 부울; true 경우 println, printf, 또는 포맷 방법 출력 버퍼

+1

이것은 성능에있어 정말로 나쁜 생각입니다. –

+0

@MirkoAdari 예 true이지만 현재 프로그램이 성능을 필요로하지 않는 것 같습니다. 그게 내가 왜 제안했는지. 어쨌든 유효한 포인트는 게시물에 포함됩니다. –

+0

감사합니다. –

1

PrintWriter 메모리 버퍼에서 파일에 쓸 내용을 플러시해야합니다. 당신은 또한 항상 가까이 (자료) 자원이 별도로 잠금 또는 OS에 따라 파일에 남아 있습니다해야 어떤 경우

out.flush(); 

. close()도 변경 사항을 자동으로 삭제합니다.

2

을 당신은 당신의 PrintWriter 개체를 닫지 않은 플래시합니다.

out.close(); 

을 (당신의 OutputStream에 따라) 당신은 당신이 출력이 콘솔에 기록 그래서를 닫아야합니다 다음

PrintWriter out = new PrintWriter(System.out); 
... 
... 
... 
out.close(); 

이 경우에도 콘솔이나 파일에 반영 할 수있는 스트림을 닫아야합니다 .
따라서 스트림을 닫으면 파일에 기록됩니다.

관련 문제