简体   繁体   English

Thread.sleep()和FileWriter()

[英]Thread.sleep() and FileWriter()

I want to make a java program that writes every 5 seconds to a file. 我想制作一个每5秒写入一个文件的Java程序。 Now the problem with this code is that after "Thread.sleep(5000)", "bw.write(s)" writes nothing to "b.txt" file and it remains empty. 现在,此代码的问题在于,在“ Thread.sleep(5000)”之后,“ bw.write(s)”未将任何内容写入“ b.txt”文件,并且该文件保持为空。 Please anyone tell me what is happening. 请任何人告诉我发生了什么事。

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");}

}
}

} }

You need to call flush() after the write() . 您需要在write()之后调用flush() write() It's called BufferedWriter because it caches data in a buffer and unless you force it to flush, it may decide that it's not time to actually write anything yet. 之所以称为BufferedWriter是因为它将数据缓存在缓冲区中,除非您强制对其进行刷新,否则它可能会决定现在还不该实际写任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM