日期:2014-05-20  浏览次数:20670 次

新手求救,对PrintWriter的迷惑
PrintWriter的print(打印)和writer(写入)方法看上去能做同样的事:
import java.io.*;

class W
{
public static void main(String[] args) throwsException {
PrintWriter pw = new PrintWriter(new FileOutputStream("F:/1.txt"));
pw.write("write.");
pw.println("println.");
pw.print("print.");
pw.close();
}
}

import java.io.*;
import java.util.*;

class R
{
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(new File("F:/1.txt"));
while(s.hasNextLine()) {
System.out.println(s.nextLine());
}
s.close();
}
}

Output:write.println.
  print

打印和写入操作有什么(本质)区别啊?如何防止混用.

------解决方案--------------------
看看PrintWriter的实现吧.
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
print只是先对s==null转换为"null"
public void println(String x) {
synchronized (lock) {
print(x);
println();
}
}
println只是保证print, println同步执行.

其实同样都是拿到一个outputstream进行写入,哪么具体就要看你的outputstream来自那里了.