现在的位置: 首页 > 综合 > 正文

Socket PrintWriter 中 write() 与 print() 的区别

2013年10月12日 ⁄ 综合 ⁄ 共 592字 ⁄ 字号 评论关闭
try {
			PrintWriter pw = response.getWriter();
			
			int x = 98;
			
			pw.write(x);
			
			pw.print(x);
			
		} catch (IOException e) {
			e.printStackTrace();
		}

 

输出:b  98

最终都是重写了抽象类Writer里面的write方法
print方法可以将各种类型的数据转换成字符串的形式输出。重载的write方法只能输出字符、字符数组、字符串等与字符相关的数据。
查看一下源码(java.io.PrintWriter):

1:write方法:

 public void write(int c) {  

  1. try {  
  2.     synchronized (lock) {  
  3.  ensureOpen();  
  4.  out.write(c);  
  5.     }  
  6. }  
  7. catch (InterruptedIOException x) {  
  8.     Thread.currentThread().interrupt();  
  9. }  
  10. catch (IOException x) {  
  11.     trouble = true;  
  12. }  
  13.    }  

 

2:print方法:

  

  1. public void print(int i) {  
  2. rite(String.valueOf(i));  
  3.   }  

 

抱歉!评论已关闭.