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));
}