Is it ok to use same file writer for writing different files

By : Jay

There's a loop where we get certain data. Depending on the data, file writer needs to write to different files.

Is it a good practice?

By : Jay


You'll have to have a FileWriter per file. So you'll have an array/list/some sort of collection of FileWriters. Not a problem so long as:

  1. you manage closing of all of these properly (think about what happens when an exception gets thrown - you should probably close all FileWriters in a finally{} block or similar)
  2. Operating systems will have limits on the maximum number of files open. I suspect from your question that you won't encounter this problem, but it's worth looking for info on the maximum number of file descriptors per-process for your particular OS.

If you are referring to, then the answer is that you can't. A FileWriter instance is tied to the file that you initialised it with.

If you're talking about your own file writer class, then the answer is more subjective as it depends entirely on your situation - which you will need to elaborate. But generally, if you're thinking of keeping writers open, then consider the possiblity that you may lose data if you don't close the file after writing but instead hang on to the instance.

Since it's not possible to have one FileWriter object to write to different files, I'd say it's not good form.

Did you mean that you have a FileWriter variable that references different FileWriter objects writing to a different file each?

That depends on the use case. If they are all writing similar data to files that have similar meanings then it might be OK.

But then again: if your method writes to more than one file, then you probably need to refactor it anyway.

This video can help you solving your question :)
By: admin