Java

Moderators: zibadian
Number of threads: 7818
Number of posts: 18218

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
How to keep stream open Posted by Wallace Yang on 13 Feb 2011 at 8:59 AM
Hi:

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) {
try{
FileWriter outfile = new FileWriter(fileList[whichFile], true);
BufferedWriter out = new BufferedWriter(outfile);
out.write("" + data+"\n");
out.close();
} 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
try{
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 + "\n"); I get an error.

Thanks. Your time and expertise is much appreciated.

Wallace
Report
Re: How to keep stream open Posted by silveredge52 on 14 Feb 2011 at 8:57 AM
Hey,
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



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.