Printwriter和OutputStream有什么区别? [英] What's the difference between Printwriter and OutputStream

查看:377
本文介绍了Printwriter和OutputStream有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我们有PrintWriter

  java.io.File f = new java.io.File(s.txt ); 

java.io.PrintWriter out = new java.io.PrintWriter(f);

out.print(5);

out.print(7);

out.close();

然后我们有outputstream

  java.io.File f = new java.io.File(s.txt); 

java.io.FileOutputStream out = new java.io.FileOutputStream(f);

out.write(5);

out.write(7);

out.close();

有什么不同?

解决方案

OutputStreams 适用于二进制数据。编写者(包括 PrintWriter )是为了 text 数据的。 您可能看不到当你打电话给 PrintWriter.write(int)写单个字符时,你的具体情况会有所不同 - 如果你使用的字符编码只是映射字符字节,对于小于127的字符,则会看到相同的结果。但是如果你给它一个不同的编码,那么你就会看到一个区别。



PrintWriter 也是不同的,因为它可以抑制IO异常,就像 PrintStream 一样,它是相当于 PrintWriter 。


First,we have PrintWriter

java.io.File f=new java.io.File("s.txt");

   java.io.PrintWriter out=new java.io.PrintWriter(f);

   out.print(5);

   out.print(7);

   out.close();

Then we have outputstream

 java.io.File f=new java.io.File("s.txt");

 java.io.FileOutputStream out=new java.io.FileOutputStream(f);

   out.write(5);

   out.write(7);

   out.close();

Whats the difference?

解决方案

OutputStreams are meant for binary data. Writers (including PrintWriter) are meant for text data.

You may not see the difference in your specific situation as you're calling PrintWriter.write(int) which writes a single character - if the character encoding you're using just maps characters to the same byte, for characters less than 127, then you'll see the same result. But if you give it a different encoding, then you'll see a difference.

PrintWriter is also different in that it suppresses IO exceptions - as does PrintStream, which is the binary stream equivalent of PrintWriter.

这篇关于Printwriter和OutputStream有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆