package mobvista.dmp.datasource.eggplants; import com.google.common.io.Closeables; import org.apache.commons.io.IOUtils; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * author: houying * date : 17-3-15 * desc : */ public class WriteFileThread implements Runnable { private final BufferedWriter writer; private final BlockingQueue<String> queue; private volatile boolean stop; public WriteFileThread(String file, BlockingQueue<String> queue) throws IOException { this.writer = new BufferedWriter(new FileWriter(file)); this.queue = queue; this.stop = false; } @Override public void run() { while(true) { if (stop && queue.isEmpty()) { break; } try { String line = queue.poll(1, TimeUnit.SECONDS); if (line == null) { continue; } writer.write(line); writer.newLine(); writer.flush(); } catch (InterruptedException e) { break; } catch (IOException e) { System.out.println("写文件失败"); break; } } try { writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("write thread exit"); } public void stop() { this.stop = true; } }