Java(字符流使用)

尽管字节流提供了处理任何类型数据输入/输出操作的足够功能,但它门不能直接操作Unicode字符。一般文本文件适合用字符流,提供直接的字符输入/输出支持是必要的。

1.文件输入/输出字符流
FileReader类是一个以字符方式读取文件内容的字符输入流。
构造函数
FileReader(String filePath)
FileReader(File fileObj)
当指定文件不存在时,每一个都能引发一个FileNotFoundException异常,这里,filePath是一个文件的完整路径,fileObj是描述该文件的File对象。
FileWriter(String filePath)
FileWriter(String filePath,boolean append)
FileWriter(File fileObj)
这里,filePath是文件完整路径,fileObj是描述该文件的File对象。如果append为true,输出内容附加到文件尾,只有一个参数的构造方法,默认会覆盖文件内容。
FileWriter类的创建不依赖于文件存在的与否,如果文件不存在,则创建一个文件,然后打开它,作为输出。如果试图打开一个只读文件,则会引发一个IOException异常。
FileReader重写了抽象类Reader读取数据的方法。
public int read()读取单个字符
public int read(char[] b)将字符读入数组
public int read(char[] b,int off,int len)将字符读入数组中的某一部分。
这些方法在读取数据时,遇到输入流结束则返回-1.
FileWriter 重写了抽象类Writer写数据的方法。
public void write(char[] b)写入字符数组
public void write(char[] b,int off,int len)写入字符数组的某一部分
public void write(int b)写入单个字符
b是int类型,占用4个字节,要写入的字符包含在给定整数值的16个低位中,16个高位被忽略。

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.annotation.processing.Filer;

public class FileReaderWriterDemo {
    public static void main(String[] args)throws IOException {
        File file=new File("C:/Users/JACK_JYH/workspace/Test/src/Main/FileReaderWriterDemo.java");
        FileReader fileReader=new FileReader(file);
        FileWriter fout=new FileWriter("C:/Users/JACK_JYH/workspace/Test/src/Main/copy-of-file.txt");
        System.out.println("Current charset is :"+fileReader.getEncoding());
        int n=(int)(file.length()/30);
        System.out.println("First "+n+"char of the file one read() at a time");
        for(int i=0;i<n;i++)
        {
            fout.write(fileReader.read());
        }
        System.out.println("Reading the next "+n+"with one read(b[])");
        char b[]=new char[n];
        if(fileReader.read(b)!=n)
        {
            System.err.println("couldn't read "+n+"bytes.");
        }
        fout.write(b);
        System.out.println("Reading the rest chars with read(b[],offset,len)");
        int count=0;
        while((count=fileReader.read(b,0,n))!=-1)
            fout.write(b,0,count);
        fileReader.close();
        fout.flush();
        fout.close();
    }

}

有问题Exception in thread “main” java.io.FileNotFoundException: C:\Users\JACK_JYH\workspace\Test\src\Main\FileReaderWriterDemo。java (系统找不到指定的文件。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileReader.(Unknown Source)
at Main.FileReaderWriterDemo.main(FileReaderWriterDemo.java:13)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值