问题
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 newFixedThreadPool
of 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.
回答1:
but in the loop it just overwrites the file.
Well yes - you're creating the FileOutputStream
in the loop. If you create the FileOutputStream
(and the OutputStreamWriter
) before the loop, then just do the writing in the loop, it will create a single file for the whole operation.
Note that the close
call should be in a finally
block 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:
FileOutputStream fo = new FileOutputStream(file);
to
FileOutputStream fo = new FileOutputStream(file, true);
The second argument, as per the documentation, states whether to append (true) or overwrite (false).
来源:https://stackoverflow.com/questions/12293707/writing-to-the-same-file-not-overwriting