out.write()和out.print()之间的确切区别是什么?

Kum*_*ani 14 java servlets printwriter

在我的servlet中,我给了两个out.printout.write.但两者都在浏览器中打印.

是什么这两个和何时使用之间的确切差异out.printout.write

Boh*_*ian 14

基本的区别是out.write()如果你传递一个null 就会爆炸:

String s = null;
out.print(s); // outputs the text "null"
out.write(s); // NullPointerException
Run Code Online (Sandbox Code Playgroud)


JNL*_*JNL 9

PrintWriter:

public void write(String s)

写一个字符串.此方法不能从Writer类继承,因为它必须抑制I/O异常.

print方法具有更高的抽象级别.

public void print(String s)

打印一个字符串.如果参数为null,则打印字符串"null".否则,根据平台的默认字符编码将字符串的字符转换为字节,并且这些字节的写入方式与write(int)方法完全相同.

希望这可以帮助.


小智 6

有三个主要差异:

1)如果您尝试使用out.write()打印String的空值,它将抛出NullPointerException,out.print()将只是作为字符串打印NULL.

 String name = null;
 out.write(name); // NullPointerException
 out.print(name); // 'Null' as text will be printed
Run Code Online (Sandbox Code Playgroud)

2)out.print()可以打印布尔值,但out.write()不能.

boolean b = true;
out.write(b); // Compilation error
out.print(b); // 'true' will be printed 
Run Code Online (Sandbox Code Playgroud)

3)如果使用的是out.write(),则根本无法放置算术运算代码,但out.print()提供了支持.

out.write(10+20); // No output will be displayed.
out.print(10+20); // Output '30' will be displayed. 
Run Code Online (Sandbox Code Playgroud)