2014-10-25 5 views
0

제 코드에서는 두 번째 단어부터 시작해서 그 반대의 단어를 모두 사용해야합니다. 다른 클래스/스레드는 자신의 일을 잘하고 있습니다. 출력을 콘솔 창에 인쇄 할 수 있으며 올바르게 출력됩니다. 그러나 텍스트 파일에 쓰려고 할 때마다 바탕 화면에 출력물이 생성되지 않습니다.BufferedWriter가 파일에 대한 출력을 생성하지 않습니다.

내 코드 :

package ProducerConsumerAssignment; 

import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileWriter; 
import java.io.IOException; 

import java.util.concurrent.BlockingQueue; 

/** 
* 
* @author Tyler Weaver 
*/ 
public class WordWriter implements Runnable { 

    private final String END_FLAG = "Terminate the queue"; 
    private static BlockingQueue<CharSequence> in; 
    private final File output; 

    /** 
    * Constructs a WordWriter object 
    * 
    * @param file the file to write words to 
    * @param queue the blocking queue to retrieve words from 
    */ 
    public WordWriter(final File file, BlockingQueue queue) { 
     output = file; 
     in = queue; 
    } 

    /** 
    * Executes when being called in a thread 
    */ 
    @Override 
    public void run() { 
     boolean isInterrupted = false; 

     while (!isInterrupted) { 
      try (BufferedWriter out = new BufferedWriter(new FileWriter(output))) { 
       CharSequence word = in.take(); 

       if (word.toString().equalsIgnoreCase(END_FLAG)) 
        Thread.currentThread().interrupt(); 

       out.write(word.toString() + " "); 
       System.out.printf("%s%n", word); 
      } catch (IOException ex) { 
       System.err.printf("Error closing the file!%n%s%n", ex); 
      } catch (InterruptedException ex) { 
       isInterrupted = true; 
      } 
     } 
    } 
} 
+0

사용중인 java 버전은 무엇입니까? 당신은 작가를 autoclose하기 위해 try-with를 사용하고 있습니까? http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – RNJ

+0

Java 1.8이 있습니다. 예, 나는 autoclose 작가를 시도하고있었습니다. –

+0

당신은 out.write (...) 후에 플러시를 호출해야합니다 – bestsss

답변

1

당신은 모든 반복에 BufferedWriter을 닫는.

BufferedWriter 개체를 while 루프 밖으로 이동하고 끝에 BufferedWriter.close()을 호출 할 수 있습니다.

BufferedWriter writer = new BufferedWriter(new FileWriter(String)); 
while (true) { 
    CharSequence word = in.take(); 
    if (word.toString().equalsIgnoreCase(END_FLAG)) { 
     break; 
    } 
    try { 
     writer.write(word + " "); 
    } catch (IOException io) { 
     break; 
    } 
} 
writer.close(); 
+0

그게 문제라고 생각하지 않습니다. 물론 나쁜 프로그래밍입니다. 하지만 그건 문제가 아닙니다. 파일은 매 반복마다 열리고 버퍼에 기록되며 닫힙니다. 그런 다음 다시 열리고 쓰여지고 닫힙니다. 어떻게 그게 문제 야? –

+0

@Aditya 덮어 씁니다. –

+0

하지만 질문은 '바탕 화면에있는 텍스트 파일에 글을 쓰려고 할 때마다 출력이 나오지 않습니다.'라는 말입니다. 즉, 파일은 한 번도 쓰지 않습니다. 그러나 당신의 말에 따르면이 프로그램은 첫 번째 반복에서 파일에 기록하고 이후의 반복마다 덮어 씁니다. 즉, 파일 끝에 마지막 행이 있어야합니다. 아니? –