PrintWriter和BufferedWriter的使用区别

BufferedWriter:将文本写入字符输出流,缓冲各个字符从而提供单个字符,数组和字符串的高效写入。通过write()方法可以将获取到的字符输出,然后通过newLine()进行换行操作。BufferedWriter中的字符流必须通过调用flush方法才能将其刷出去。并且BufferedWriter只能对字符流进行操作。如果要对字节流操作,则使用BufferedInputStream。


PrintWriter:向文本输出流打印对象的格式化表示形式(Prints formatted representations of objects to a text-output stream)。PrintWriter相对于BufferedWriter的好处在于,如果PrintWriter开启了自动刷新,那么当PrintWriter调用println,prinlf或format方法时,输出流中的数据就会自动刷新出去。PrintWriter不但能接收字符流,也能接收字节流。


Socket编程中,尽量用PrintWriter取代BufferedWriter,下面是PrintWriter的优点:

1. PrintWriter的print、println方法可以接受任意类型的参数,而BufferedWriter的write方法只能接受字符、字符数组和字符串;

2. PrintWriter的println方法自动添加换行,BufferedWriter需要显示调用newLine方法;

3. PrintWriter的方法不会抛异常,若关心异常,需要调用checkError方法看是否有异常发生;

4. PrintWriter构造方法可指定参数,实现自动刷新缓存(autoflush);

5. PrintWriter的构造方法更广。

-------------------------------------------------------------------

扫描二维码关注公众号,回复: 3874738 查看本文章

总结:

在使用BufferedReader中的readLine方法接收BufferedWriter中的字符流时,由于readLine是在读取到换行符的时候才将整行字符返回,所以BufferedWriter方法在录入一段字符后要使用newLine方法进行一次换行操作,然后再把字符流刷出去。而PrintWriter由于可以开启自动刷新,并且其中的println方法自带换行操作。所以代码实现起来要比BufferedWriter简单一些。

PrintWriter和BufferedWriter都是继承java.io.Writer,所以很多功能都一样。不过PrintWriter提供println()方法可以写不同平台的换行符,而BufferedWriter可以任意设定缓冲大小。OutputStream可以直接传给PrintWriter(BufferedWriter不能接收),如:  

PrintWriter out = new PrintWriter(new BufferedOutputStream(
    new FileOutputStream("foo.out")));
或者用OutputStreamWriter来将OutputStream转化为Wrtier.这时就可以用BufferedWriter了。JDK API documents中都写的很清楚了。

猜你喜欢

转载自blog.csdn.net/arno_dzl/article/details/76601852