PrintWriter类的println()方法和wirte()方法有什么区别?
API中有
void println(String x)
打印 String,然后终止该行。
void write(String s)
写入字符串。
很奇怪为什么要同时提供2个方法,测试后返现都是写入字符串,不知道有什么区别?
谁能写个简单的测试类让我seesee
API中有
void println(String x)
打印 String,然后终止该行。
void write(String s)
写入字符串。
很奇怪为什么要同时提供2个方法,测试后返现都是写入字符串,不知道有什么区别?
谁能写个简单的测试类让我seesee
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();
}
}
如: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)则是对象的序列化字节流。
以上仅供你参考
/**
* 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);
}