字符输入输出流---抽象的字符输入流Reader类、抽象的字符输出流Writer类的使用总结

前一篇总结了字节输入输出流的使用,这一篇是对字符输入输出流的总结。

利用字符流java.io.Reader、java.io.Writer类可以直接实现字符数组、字符串的输入、输出。这两个类都是抽象类,不能直接使用,需要使用其子类向上转型完成实例化后,才可以使用。

(1)、字符输入流Reader的常用方法:(在对中文数据进行读取时,可以直接使用字符输入流Reader类进行操作)

       作用:将字符数据读入到数组中;

public int read()  throws IOException;  //读取一个字符,返回范围是0-65535之间的int值,如果读到文件流的末尾返回-1;

public int read(char[ ] cbuf)  throws IOException; //读入多个字符到字符数组cbuf中,如果读到文件流的末尾返回-1;

public int read(char[ ] cbuf,int off,int len)  throws IOException;//读取len个字符存放到字符数组从off开始的位置中;

public void mark(int readAheadLimit);    //标记输入流的当前位置;

public boolean markSupported();          //测试输入流是否支持mark()方法;

public void reset();      //重新定位输入流;

public long skip(long n); //从输入流中最多向后跳n个字符,返回实际跳过的字符个数;

public boolean ready();   //返回输入流是否做好读的准备;

public void close();      //关闭输入流;

要想调用上面的方法,因为Reader是抽象类,需要使用其子类java.io.FileReader类向上转型完成实例化,才可以使用;

FileReader子类的构造方法:public  Reader FileReader(File file)  throws FileNotFoundException; //定义要读取得文件路径

使用举例:

import ...

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

     File file=new File("d:"+File.separator+"Reader"+File.separator+"Reader.txt");
     if(file.exists()){
        //通过子类向上转型完成实例化
        Reader r=new FileReader(file);
        //字符数组用于接收读取的字符
        char data[]= new char[1024];
        //将制定路径文件中的字符读入到字符数组data中
        int len=r.read(data);
        r.close();
        //将部分字符数组转换为字符串输出
        System.out.println(new String(data,0,len));
     }
   }
}

输出内容:欢迎使用字符输入输出流!

(2)、字符输出流Writer类常用方法

作用:将字符数据输出到文件;

public void write(String str) throws IOException;     //输出字符串数据;
public void write(char[]  cbuf) throws IOException;  //输出字符数组数据; 
public Writer append(CharSequence csq) throws IOException;//追加数据;
public void flush( ) throws IOException; //强制刷新,输出数据;
public void close( ) throws IOException;   //流操作完毕后必须关闭,否则容易造成内存泄漏;

 同样,要想调用上面的方法,因为Writer类是抽象类,需要使用其子类java.io.FileWriter类向上转型完成实例化,才可以使用;

FileWriter子类的构造方法:

public  FileWriter(File file)  throws IOException; //定义输出文件

public  FileWriter(File file,boolean append)  throws IOException; //设置输出文件以及是否进行数据追加;

使用举例:

import ...

public class WriterDemo{
   public static void main(String[] args) throws Exception{
     //定义要输出的文件路径
     File file=new File("d:"+File.separator+"Reader"+File.separator+"Writer.txt");
     //判断目录是否存在
     if(!file.getParentFile().exists()){
        //创建文件目录
        file.getParentFile().mkdirs();
     }
     Writer out=new FileWriter(file);
     String str="欢迎使用字符输入输出流!";
     //输出字符串数据到文件
     out.write(str);
     out.close();
   }
}
发布了9 篇原创文章 · 获赞 0 · 访问量 1433

猜你喜欢

转载自blog.csdn.net/luqingshuai_eloong/article/details/104224541
今日推荐