简体   繁体   中英

Thread.sleep() and FileWriter()

I want to make a java program that writes every 5 seconds to a file. 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. 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() . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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