【问题标题】:Thread.sleep() and FileWriter()Thread.sleep() 和 FileWriter()
【发布时间】:2018-04-15 11:01:50
【问题描述】:

我想制作一个每 5 秒写入文件的 java 程序。现在 这段代码的问题是在“Thread.sleep(5000)”之后,“bw.write(s)”没有向“b.txt”文件写入任何内容并且它仍然是空的。请任何人告诉我发生了什么。

import java.lang.*;
import java.io.*;
public class Threading{
public static void main(String args[]){
//File f=new File("Rand2.java");
String s="hello";
BufferedWriter bw=null;
FileWriter fw=null;

fw=new FileWriter("b.txt");
bw=new BufferedWriter(fw);


while(true){

    try{
        Thread.sleep(5000);

    }catch(InterruptedException ie){}
    try{    
    bw.write(s);
    //bw.write((int)f.length());
    System.out.println("Hey! I just printed something.");
    }catch(IOException io){System.out.println("IOException");}

}
}

}

【问题讨论】:

  • 其实对我有用
  • 是的!有用。谢谢。
  • @minizibi 我通过添加使其工作的代码错误地编辑了问题。编辑已被删除,可重现。

标签: java multithreading filewriter bufferedwriter


【解决方案1】:

您需要在write() 之后调用flush()。之所以称为BufferedWriter,是因为它将数据缓存在缓冲区中,除非您强制它刷新,否则它可能会决定现在还不是真正写任何东西的时候。

【讨论】:

    猜你喜欢
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2012-12-13
    相关资源
    最近更新 更多