[求助]PrintWriter类的println()方法和wirte()方法有什么区别?

Steve_Samuelson 2008-05-04 04:34:08
PrintWriter类的println()方法和wirte()方法有什么区别?
API中有
void println(String x)
打印 String,然后终止该行。
void write(String s)
写入字符串。
很奇怪为什么要同时提供2个方法,测试后返现都是写入字符串,不知道有什么区别?
谁能写个简单的测试类让我seesee
...全文
271 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
super_marshal 2008-12-26
  • 打赏
  • 举报
回复
java源代码:
/**
* Print a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>String</code> to be printed.
*/
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
/**
* Print a string. If the argument is <code>null</code> then the string
* <code>"null"</code> 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
* <code>{@link #write(int)}</code> method.
*
* @param s The <code>String</code> to be printed
*/
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
lizheaaaabbbb 2008-12-26
  • 打赏
  • 举报
回复
非常谢谢大家伙和楼主,众人拾柴火焰高。希望自己也能为大家提供更多的帮助!
findself 2008-05-05
  • 打赏
  • 举报
回复
学习学习,顶
hkfxp 2008-05-05
  • 打赏
  • 举报
回复
一个简单的问题我.....怎么都不会?!再看看API去
老紫竹 2008-05-05
  • 打赏
  • 举报
回复
一个会自动刷新,另一个则不会!
loujianchengdd 2008-05-04
  • 打赏
  • 举报
回复
write是向一个byet[]中写值一般,而print是写一个字符串
云上飞翔 2008-05-04
  • 打赏
  • 举报
回复
答:区别当然大啦。write(...)的意图是按JAVA基本类型进行输出。
如:write(12.6d)将输出double的8个字节。而print(12.6d)永远输出的是值的“字符串表示的形式”,
即:它输出的是“12.6”这个字节串。再如:boolean a=true;write(a)输出的是一个字节。而:print(a)输出
的"true"这个字符串。记住:print(...)永远输出的参数的字符串表示的形式。所以:若是对象o,
则:print(o)输出的是o.toString(),而:write(o)则是对象的序列化字节流。
以上仅供你参考
Steve_Samuelson 2008-05-04
  • 打赏
  • 举报
回复
换行不是主要问题。期待精品回复!
ilrxx 2008-05-04
  • 打赏
  • 举报
回复
我个人觉得除了println换行以外没什么区别,可能是是因为write方法多于print能控制写入部分字符串:
public static void main(String[] args) throws IOException {
String str = "我爱中国";
try {
PrintWriter pw = new PrintWriter(new File("G:\\file\\outfile.txt"));
BufferedWriter bw = new BufferedWriter(pw);
pw.write(str);//pw.println(str);
bw.flush();
pw.flush();
bw.close();
pw.close();
} catch (FileNotFoundException e) {
System.out.println("文件不存在!");
e.printStackTrace();
}


}
yangxiao_jiang 2008-05-04
  • 打赏
  • 举报
回复
楼上说的是一个区别

另外,println中调用了write,就是println会对打印的东西比write多些判断。
dracularking 2008-05-04
  • 打赏
  • 举报
回复
别的先不管 第一个有换行就是个区别

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧