java Printwriter 和 OutputStream 有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6883715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between Printwriter and OutputStream
提问by rena-c
First,we have PrintWriter
首先,我们有 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?
有什么不同?
回答by Jon Skeet
OutputStreams
are meant for binarydata. Writers (including PrintWriter
) are meant for textdata.
OutputStreams
用于二进制数据。Writers(包括PrintWriter
)用于文本数据。
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, thenyou'll see a difference.
当您调用PrintWriter.write(int)
它写入单个字符时,您可能看不到具体情况的差异- 如果您使用的字符编码只是将字符映射到相同的字节,对于小于 127 的字符,那么您会看到相同的结果。但是如果你给它一个不同的编码,那么你会看到不同。
PrintWriter
is also different in that it suppresses IO exceptions - as does PrintStream
, which is the binary stream equivalent of PrintWriter
.
PrintWriter
不同之处还在于它抑制 IO 异常 - 也是如此PrintStream
,它是PrintWriter
.
回答by Christian Vielma
From this java2novice.com linkI extracted the following, that is similar to what Jon said:
我从这个java2novice.com 链接中提取了以下内容,这类似于 Jon 所说的:
ServletOutputStream:ServletResponse.getOutputStream() returns
a ServletOutputStream
suitable for writing binary data in the response. The servlet
container does not encode the binary data, it sends the raw data
as it is.
ServletOutputStream:ServletResponse.getOutputStream() returns
一个ServletOutputStream
适合在响应中写入二进制数据。servlet 容器不对二进制数据进行编码,而是按原样发送原始数据。
PrintWriter:ServletResponse.getWriter()
returns PrintWriter
object which sends
character text to the client. The PrintWriter
uses the character
encoding returned by getCharacterEncoding()
. If the response's
character encoding has not been specified then it does default
character encoding.
PrintWriter:ServletResponse.getWriter()
返回PrintWriter
向客户端发送字符文本的对象。在PrintWriter
使用由返回的字符编码getCharacterEncoding()
。如果未指定响应的字符编码,则它执行默认字符编码。