vivek
vivek

Reputation: 11

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

}
}

}

Upvotes: 0

Views: 416

Answers (1)

user3237736
user3237736

Reputation: 857

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.

Upvotes: 1

Related Questions