Here is my snippet.
File file = new File(Thread.currentThread().getName());
for(each element of the list){
createStringWriterAndPopulateDataToBeWritten
FileOutputStream fo = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(fo,"UTF-8");
out.write(sw.toString());
out.close();
}
Now say i have a newFixedThreadPoolof size S; i pass this thread pool a list of work to be done. Now everytime a thread is called, it creates a file with name as the name of thread and then writes to it, but in the loop it just overwrites the file.
How can make it work to append and not overwrite, even if the Thread is called again, which can very much happen in this case since my list of Work to the thread pool is pretty long.
Note:Each element of the list of jobs passed to the ThreadPool is also a list and that is why there a for loop in the snippet.
Thanks.
Well yes – you’re creating the
FileOutputStreamin the loop. If you create theFileOutputStream(and theOutputStreamWriter) before the loop, then just do the writing in the loop, it will create a single file for the whole operation.Note that the
closecall should be in afinallyblock so you close the writer even if the code throws an exception.If you also need to append to the file if this code is called again, just change this:
to
The second argument, as per the documentation, states whether to append (true) or overwrite (false).