文件操作二

一、             字符输入流

Reader:字符输入流。示例代码如下:

import java.io.File;

import java.io.FileReader;

import java.io.Reader;

 

public class ReaderDemo {

 

   /**

    * @param args

    * @throws Exception 

    */

   public static void main(String[] args) throws Exception {

     // TODO Auto-generated method stub

     File file=new File("c:"+File.separator+"hi.txt");

     Reader r=new FileReader(file);

     char[] c=new char[(int) file.length()];

     int len=r.read(c);

     System.out.println(new String(c,0,len));

     r.close();

   }

 

}

二、BufferedReader操作流:
InputStreamReader:字节输入变为字符流

OutputStreamWriter:字符的输出流变为字节的输出流

使用BufferedReader完成键盘输入:

import java.io.BufferedReader;

import java.io.InputStreamReader;

 

public class BufferedReaderDemo {

   public static void main(String[] args) throws Exception {

     // TODO Auto-generated method stub

     BufferedReader buf=null;

     System.out.println("输入内容:");

     buf=new BufferedReader(new InputStreamReader(System.in));

     System.out.println(buf.readLine());

   }

}

 

三、             打印流:

打印流分为:PrintReader和PrintWriter。

使用PrintStream示例

import java.io.File;

import java.io.FileOutputStream;

import java.io.PrintStream;

 

public class PrintWriterDemo {

   public static void main(String[] args) throws Exception {

     // TODO Auto-generated method stub

     File file=new File("c:"+File.separator+"hi.txt");

     PrintStream pr=new PrintStream(new FileOutputStream(file),true);

     pr.print("\r\nhello");

     pr.print("\r\nworld");

     pr.close();

   }

}

示例代码二:

import java.io.PrintStream;

 

public class PrintWriterDemo2 {

 

   /**

    * @param args

    * @throws Exception 

    */

   public static void main(String[] args) throws Exception {

     // TODO Auto-generated method stub

     PrintStream pr=new PrintStream(System.out);

     pr.print("\r\nhello");

     pr.print("\r\nworld");

     pr.close();

   }

 

}

 

posted @ 2011-08-10 11:40  rorshach  阅读(126)  评论(0编辑  收藏  举报