java.io.PrintWriter 中 write() 与 print() 的区别

try {  
            PrintWriter pw = response.getWriter();  
              
            int x = 98;  
              
            pw.write(x);  
              
            pw.print(x);  
              
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
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方法:

  view plaincopy to clipboardprint?
 public void write(int c) {  
try {  
    synchronized (lock) {  
 ensureOpen();  
 out.write(c);  
    }  
}  
catch (InterruptedIOException x) {  
    Thread.currentThread().interrupt();  
}  
catch (IOException x) {  
    trouble = true;  
}  
   } 
  public void write(int c) {
 try {
     synchronized (lock) {
  ensureOpen();
  out.write(c);
     }
 }
 catch (InterruptedIOException x) {
     Thread.currentThread().interrupt();
 }
 catch (IOException x) {
     trouble = true;
 }
    }
 

2:print方法:

  view plaincopy to clipboardprint?
public void print(int i) {  
rite(String.valueOf(i));  
  } 

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/lihan6415151528/archive/2009/02/20/3914732.aspx

你可能感兴趣的:(Java)