What is the exact difference between out.write() a

2020-01-30 11:35发布

In my servlet I gave both out.print and out.write. but both prints in the browser.

What is the exact difference between these two and when to use out.print and out.write ?

9条回答
何必那么认真
2楼-- · 2020-01-30 12:11

out.write(-) vs out.print(-)

One more difference is out.write(-) method just write data or object to browser like a file. You can not write any statement like out.write(10*20); but we do this with out.print(10*20);

查看更多
【Aperson】
3楼-- · 2020-01-30 12:16

The out variable in your case is most likely refers to a PrintWriter

Just compare the description of write...

public void write(String s)

Write a string. This method cannot be inherited from the Writer class because it must suppress I/O exceptions.

... with the description of println ...

public void println(String x)

Print a String and then terminate the line. This method behaves as though it invokes print(String) and then println().

... and print ...

public void print(String s)

Print a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

All in all I'd say that the print methods work on a higher level of abstraction and is the one I prefer to work with when writing servlets.

查看更多
三岁会撩人
4楼-- · 2020-01-30 12:20

I simply know it as like this:

out.println() is method of javax.​servlet.​jsp.​JspWriter

out.write() is method of java.io.Writer

查看更多
登录 后发表回答