File 对象的相关操作和访问(2)

来源:互联网 发布:鄂维南 大数据 编辑:程序博客网 时间:2024/06/09 14:39

 PrintStream类

  PrintStream类提供了以文本格式来显示数据的功能,和其他的流类相比,在很多情况下,这显然更符合我们的实际需要.其构造方法是:

  public PrintStream(OutputStream out):由out所指定的OutputStream对象创建一个输出流

  void close():关闭流对象,释放与该流对象有关的任何资源

  void flush():将缓冲区的数据立刻写入流

  void print(boolean b):向流中写入一个布尔类型的数据

  void println();向流中写入一个回车换行符

  void println(boolean x):向流中写入一个布尔数据和一个换行符

  void write(int b)将int型参数b写入流

 void write(byte[] buf,int offset,int length)将字节数组buf中从索引值为offset处开始、长度为length的数据写入流.:

下面一个例子实现了向文件中写入格式化的信息:

import java.io.*;

public class testPrintStream {
 public static void main(String args[]){
  boolean b=true;
  double d=0.14523;
  String s="I am so happy";
  String fileName="d://java//test//change.txt";
  File newFile=new File(fileName);
  try
  {
   if(!newFile.exists()){
    PrintStream ps=new PrintStream(new FileOutputStream(newFile));//创建输出流对象.
    System.out.println("create PrintStream for  "+fileName);
    ps.println(100);
    ps.println(b);
    ps.println(d);
    ps.println(s);
    ps.close();
    
    System.out.println("Data have been written into the destination file");
   }
   else
    System.out.println("output stream for "+fileName+"  already exists");
  }
  catch(IOException e){
  System.out.println(e); 
   
  }
  
  
 }

}
   打开文件d://java//test//change.txt,便可以看到其中增加了上面的格式化信息。

 

原创粉丝点击