0

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

}
}

}

xingbin
  • 27,410
  • 9
  • 53
  • 103
vivek
  • 11

1 Answers1

1

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.

user3237736
  • 845
  • 1
  • 9
  • 24