FileWrite BufferedWriter和PrintWriter相结合 [英] FileWrite BufferedWriter and PrintWriter combined
问题描述
好的,我正在学习I / O,我在其中一张幻灯片中找到了以下代码。有人可以解释为什么需要有FileWrite,BufferedWriter和PrintWriter吗?我知道BufferedWriter是缓冲输出并将其全部放在一起,但为什么他们会使用FileWriter和PrintWriter?他们几乎没有做同样的错误处理等一点点差异?
Ok so I am learning about I/O, and I found the following code in one of the slides. can someone please explain why there is a need to have a FileWrite, BufferedWriter and PrintWriter? I know BufferedWriter is to buffer the output and put it all at once but why would they use FileWriter and PrintWriter ? dont they pretty much do the same with a bit of difference in error handling etc?
还有为什么他们将 bw
传递给 PrintWriter
?
And also why do they pass bw
to PrintWriter
?
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
推荐答案
据推测他们正在使用 FileWriter
因为他们想要写入文件。 BufferedWriter
和 PrintWriter
都必须给另一个写入的作者 - 你需要一些最终的目的地。
Presumably they're using a FileWriter
because they want to write to a file. Both BufferedWriter
and PrintWriter
have to be given another writer to write to - you need some eventual destination.
(我个人不喜欢 FileWriter
,因为它不允许你指定编码。我更喜欢使用包含在 OutputStreamWriter
中的 FileOutputStream
,但这是另一回事。)
(Personally I don't like FileWriter
as it doesn't let you specify the encoding. I prefer to use FileOutputStream
wrapped in an OutputStreamWriter
, but that's a different matter.)
BufferedWriter
用于缓冲,正如你所说 - 虽然它不会缓冲所有输出,只是一个固定数量(缓冲区的大小)。它为底层作者创建了更大的写作。
BufferedWriter
is used for buffering, as you say - although it doesn't buffer all the output, just a fixed amount of it (the size of the buffer). It creates "chunkier" writes to the underlying writer.
至于使用 PrintWriter
- 好吧,暴露一些额外的方法,如 println
。我个人不喜欢它,因为它吞下异常(你必须明确检查 checkError
,它仍然没有提供详细信息,我不认为我曾经看过使用过),但这又取决于你在做什么。 PrintWriter
作为其目的地传递给 BufferedWriter
。
As for the use of PrintWriter
- well, that exposes some extra methods such as println
. Personally I dislike it as it swallows exceptions (you have to check explicitly with checkError
, which still doesn't give the details and which I don't think I've ever seen used), but again it depends on what you're doing. The PrintWriter
is passed the BufferedWriter
as its destination.
因此,您显示的部分下面的代码可能会写入 PrintWriter
,它将写入 BufferedWriter
,这将(当它的缓冲区已满,或者被刷新或关闭时)写入 FileWriter
,然后将字符数据转换为磁盘上的字节数。
So the code below the section you've shown will presumably write to the PrintWriter
, which will write to the BufferedWriter
, which will (when its buffer is full, or it's flushed or closed) write to the FileWriter
, which will in turn convert the character data into bytes on disk.
这篇关于FileWrite BufferedWriter和PrintWriter相结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!