My java code receives stream data like twitter. I need to store the data e.g. 10000 records for each file. So, I need to recreate the file writer and buffered writer to create a new file then write data on it.
    // global variables
    String stat;
    long counter = 0;
    boolean first = true;
    Date date;
    SimpleDateFormat format;
    String currentTime;
    String fileName;
    BufferedWriter bw = null;
    FileWriter fw = null;
    public static void main(String[] args) {
        String dirToSave = args[0];
        String fileIdentifier = args[1];
        createFile(dirToSave, fileIdentifier);
        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                stat = TwitterObjectFactory.getRawJSON(status);
                try {
                    if(bw!=null){
                        bw.write(stat + "\n");
                    }
                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                }
                counter++;
                if (counter == 10000) {
                    createFile(dirToSave, fileIdentifier);
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException ex) {
                       System.out.println(ex.getMessage());
                    }
                    counter = 0;
                }
            }
        };
TwitterStream twitterStream = new TwitterStreamFactory(confBuild.build()).getInstance();
    twitterStream.addListener(listener);
    // twitterStream.filter(filQuery);
    }
public static void createFile(String path, String fileIdentifier) {
        date = new Date();
        format = new SimpleDateFormat("yyyyMMddHHmm");
        currentTime = format.format(date);
        fileName = path + "/" + fileIdentifier + currentTime + ".json";
// if there was buffer before, flush & close it first before creating new file
        if (!first) {
            try {
                bw.flush();
                bw.close();
                fw.close();
            } catch (IOException ex) {
                Logger.getLogger(LocalFile_All_en.class
                        .getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            first = false;
        }
        // create a new file
        try {
            fw = new FileWriter(fileName);
            bw = new BufferedWriter(fw);
        } catch (IOException ex) {
            Logger.getLogger(Stack.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }
However, i always get error after some hours.
SEVERE: null
java.io.IOException: Stream closed
EDIT: The error message says that, these codes throw the error
if (counter == 10000) {
                    createFile(dirToSave, fileIdentifier);
...
and
bw.flush();
What is the problem of my code? or is there a better way to write stream data like this?
 
    