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

关于打印流和输出流的一点疑问
看下面两个程序
import   java.io.*;
public   class   FileOutputStream1{
public   static   void   main(String   args[])throws   Exception{
FileWriter   fw   =   new   FileWriter(new   File( "log.log "));



int   line   =   0;
for(char   c=1;c <65535;c++){
fw.write(c+ " ");
}
if(line++   >   100){
System.out.println();
line   =   0;
}
}
}

2)

import   java.io.*;
public   class   PrintStream1{
public   static   void   main(String   args[])throws   Exception{
FileOutputStream   fos   =   new   FileOutputStream(new   File( "log.log "));

PrintStream   ps   =   new   PrintStream(fos);
if(ps   !=   null){
System.setOut(ps);
}
int   line   =   0;
for(char   c=1;c <65535;c++){
System.out.print(c+ " ");
}

if(line++   > 100){
System.out.println();
line   =   0;
}
}
}

这两个程序都可以往log.log文件中写进去65534个字符,区别就是一个是通过打印流打印进去,一个通过输出流写进去。但是效果是一样的。
请问一下在实际应用中,这个“打印”和这个“写”到底有什么区别呢?就是说如果往一个文件里面写东西,是通过打印流来做,还是通过输出流来做呢,因为打印流里面是autoFlush的,所以有的时候比较方便,不用象输出流那样还要套一个bufferedoutputstream啊,呵呵,这点疑问,谢谢大家来解释。

------解决方案--------------------
A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ( '\n ') is written.

A file output stream is an output stream for writing data to a File or to a FileDescriptor. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.

简单说来就像你说的那样
printstream方便些,fileoutputstream用来写文件,两者都继承自outputstream,假如想方便一些可以用printstream,而有特殊需要则可以用fileoutputstream