Java IO知识点总结三(字符流)

在程序中一个字符等于两个字节,Java提供了Reader和Writer两个专门操作字符的类。
1.字符流输出Writer类
这里写图片描述
同样,该类本身为一个抽象类,通过其子类实现具体的操作
FileWriter的构造方法如下:
public FileWriter(File file) throws IOException

2.字符流输出实例程序如下

package stringText;

import java.io.*;

public class WriterAndReader {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        /*
         * 例1 Writer直接输出字符串
         */
        // 第一步,使用File类找到一个文件
        File f = new File("d:\\test\\1.txt");
        // 第二步,通过子类实例化父类对象
        Writer out = null;
        out = new FileWriter(f);
        // 第三步,定义字符串并输出
        String s = "  Hello World With Writer";
        out.write(s);
        // 第四步,关闭输出流
        out.close();

        /*
         * 例2 追加字符串内容
         */
        // 第一步,使用File类找到一个文件
        File f1 = new File("d:\\test\\1.txt");
        // 第二步,通过子类实例化父类对象
        Writer out1 = null;
        out1 = new FileWriter(f1, true);
        // 第三步,定义字符串并输出
        String s1 = "  Add Hello World With Writer";
        out1.write(s1);
        // 第四步,关闭输出流
        out1.close();
    }

}

3.字符输入流Reader
这里写图片描述
子类FileReader的构造方法为:
public FileReader(File file) throws FileNotFoundException
4.字符输入流事例如下

package stringText;

import java.io.*;

public class WriterAndReader {

    public static void main(String[] args) throws Exception {
        /*
         * 例1 输入流中输入字符串
         */
        //第一步,使用File类找到一个文件
        File f2=new File("d:\\test\\1.txt");
        //第二步,通过子类实例化父类的对象
        Reader reader=new FileReader(f2);//准备一个输入流对象
        //第三步,进行读写操作
        char c[]=new char[1024];
        int len=reader.read(c);     //获取文件的长度
        //第四步,关闭输入流
        reader.close();
        System.out.println("内容为:"+new String(c,0,len));

        /*
         * 例2 输入流中输入字符串(利用循环方式)
         */
        //第一步,使用File类找到一个文件
        File f3=new File("d:\\test\\1.txt");
        //第二步,通过子类实例化父类的对象
        Reader reader1=new FileReader(f2);//准备一个输入流对象
        //第三步,进行读写操作
        char c1[]=new char[1024];
        int len1=0;     //获取文件的长度
        int temp=0;     //接收读取的每一个内容
        //第四步,关闭输入流
        while((temp=reader1.read())!=-1){
            c1[len1]=(char)temp;
            len1++;
        }
        reader.close();
        System.out.println("内容为:"+new String(c1,0,len));

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值