是否可以使用同一个文件编写器来写入不同的文件
有一个循环可以让我们获取某些数据。 根据数据的不同,文件写入器需要写入不同的文件。
这是一个好的做法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于不可能使用一个 FileWriter 对象写入不同的文件,因此我认为这不是一种好的形式。
您的意思是您有一个
FileWriter
变量,该变量引用不同FileWriter
对象写入不同的文件?这取决于用例。 如果他们都将相似的数据写入具有相似含义的文件中,那么可能没问题。
但话又说回来:如果您的方法写入多个文件,那么您可能无论如何都需要重构它。
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 differentFileWriter
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.
如果您指的是
java.io.FileWriter
,那么答案是 你不能。FileWriter
实例与您初始化它的文件绑定在一起。如果您正在谈论您自己的文件编写器类,那么答案就更加主观,因为它完全取决于您的情况 - 您需要详细说明。 但一般来说,如果您正在考虑让写入器保持打开状态,请考虑如果您在写入后不关闭文件而是保留实例,则可能会丢失数据。
If you are referring to
java.io.FileWriter
, then the answer is that you can't. AFileWriter
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.
每个文件都必须有一个
FileWriter
。 因此,您将拥有一个数组/列表/某种FileWriters
集合。 只要满足以下条件,就不是问题:You'll have to have a
FileWriter
per file. So you'll have an array/list/some sort of collection ofFileWriters
. Not a problem so long as: