Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


How to keep stream open

Wallace YangWallace Yang Member Posts: 6

In my program, I need to write to many files very often when data is received. Presently, I have one method that writes data to files, where the file to be written to depends on the argument I pass it. Below is the simplified version:

void saveData(int whichFile, int data) {
FileWriter outfile = new FileWriter(fileList[whichFile], true);
BufferedWriter out = new BufferedWriter(outfile);
out.write("" + data+"
} catch(IOException e) {

The problem is that because each file to be written to, calls saveData so often, there is major inefficiency in creating and closing the streams. I would like to keep the streams open for the duration of my class. However, when I put into the constructor of my class:

//declared outfile and out as members of the class
outfile = new FileWriter(fileList[whichFile], true);
out = new BufferedWriter(outfile);
} catch(IOException e) {

out gets closed it seems when the constructor ends. So when saveData uses out.write("" + data + "
"); I get an error.

Thanks. Your time and expertise is much appreciated.



  • silveredge52silveredge52 Member Posts: 198
    I believe the problem is solved by breaking the solution into 3 elements. First element is "allocateFile". Second element is "saveData". Third element is "closeFile".

    regards, se52
Sign In or Register to comment.