java中讲讲FileReader的用法

FileReader的用法
FileReader是Reader的继承类,从字面上就可看出,它的主要功能就是能从磁盘上读入文件。read方法会一个一个字符的从磁盘往回读数据。
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。



例:2.2.1

import java.io.*;
public class TestMark_to_win {
    public static void main(String args[]) throws Exception {
        /*public int read()
         throws IOException
Reads a single character.
Overrides:
read in class Reader
Returns:
The character read, or -1 if the end of the stream has been reached
Throws:
IOException - If an I/O error occurs */
        int ii;
        FileReader in = new FileReader("c:/1.txt");
        while ((ii = in.read()) != -1) {
            System.out.println(ii);
        }
        in.close();
        FileReader in1 = new FileReader("c:/1.txt");
        while ((ii = in1.read()) != -1) {
            System.out.println((char)ii);
        }
        in1.close();
    }
}

结果:
97
98
25105
20204
97
98
a
b


a
b





例:2.2.2(一个简单的拷贝方法,初学者方便理解)
import java.io.*;
public class TestMark_to_win {
    public static void main(String[] args) throws IOException {
        File inputFile = new File("c:/1.txt");
        File outputFile = new File("c:/1_c.txt");
        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        int c;
        while ((c = in.read()) != -1)
            out.write(c);
        in.close();
        out.close();
    }
}