读书人

() PrintStream(File file)的疑惑

发布时间: 2012-12-15 15:16:03 作者: rapoo

(求助) PrintStream(File file)的疑惑
使用 PrintStream 打印数据到文件,一般都使用下面的方法:
API文档中描述为:PrintStream(OutputStream out) 参接收OutputStream对象,实例化PrintStream类

File f = new File("D:\\a.txt") 
// 向"D:\\a.txt"文件中打印内容"hello"
PrintStream ps = new PrintStream(new FileOutputStream(f));
ps.print("hello");


为什么不直接使用下面的代码呢?也有构造方法:PrintStream(File file) 直接通过一个File对象实例化PrintStream类。
File f = new File("D:\\a.txt") 
// 向"D:\\a.txt"文件中打印内容"hello"
PrintStream ps = new PrintStream(f);
ps.print("hello");


2种方法都可以正常在文件中打印内容。不知道有没有人了解两者的区别。
新人不材,请大家指教!
[最优解释]
没啥区别,你看看Java的源码就知道了:
public PrintStream(File file) throws FileNotFoundException {
this(false, new FileOutputStream(file));
init(new OutputStreamWriter(this));
}


[其他解释]
为什么不使用PrintWriter。PrintStream这个会自动转码。
引用
All characters printed by a PrintStream are converted into bytes using the platform's default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes.

读书人网 >J2SE开发

热点推荐