Why need PrintWriter?

前端 未结 3 1547
梦谈多话
梦谈多话 2021-02-06 07:40

I am really confused about the purpose of various io classes, for example, If we have BufferedWriter, why we need a PrintWriter?

BufferedReader reader = new Buff         


        
3条回答
  •  清酒与你
    2021-02-06 08:00

    They have nothing to do with each other. In all truth, I rarely use PrintWriter except to convert System.out temporarily. But anyway.

    BufferedWriter, like BufferedReader/BufferedInputStream/BufferedOutputStream merely decorates the enclosed Writer with a memory buffer (you can specify the size) or accept a default. This is very useful when writing to slow Writers like network or file based. (Stuff is committed in memory and only occasionally to disk for example) By buffering in memory the speed is greatly increased - try writing code that writes to say a 10 mb file with just FileWriter and then compare to the same with BufferedWriter wrapped around it.

    So that's BufferedWriter. It throws in a few convenience methods, but mostly it just provides this memory buffer.

    PrintWriter mostly is a simple decorator that adds some specific write methods for various types like String, float, etc, so you don't have to convert everything to raw bytes.

    Edited:

    This already has come up

提交回复
热议问题