java_25 FileReader类和FileWriter类

1.FileWriter

  1.1FileWriter 用于写入字符流。要写入原始字节流,请考虑使用 FileOutputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Demo {
    public static void main(String[] args) throws IOException{
        FileWriter fileWriter = new FileWriter("d:\\aaa.txt");
        //添加字符
        fileWriter.write(100);
        fileWriter.write(101);
        //添加字符数组
        char[] c = {'a','b','c','d'};
        fileWriter.write(c);
        fileWriter.write(c,1,2);
        //添加字符串
        fileWriter.write("hello world");
        fileWriter.flush();
        fileWriter.close();
    }
}

2.FileReader

  1.1用来读取字符文件的便捷类。FileReader 用于读取字符流。要读取原始字节流,请考虑使用 FileInputStream

  //flush  和close区别
       // flush用来刷新缓冲区的  只有字符流才需要刷新  

  字节读取

1
2
3
4
5
6
7
8
9
10
public class Demo {
    public static void main(String[] args) throws IOException{
        FileReader fileReader = new FileReader("d:\\aaa.txt");
        int len = 0;
        while((len=fileReader.read())!=-1) {
            System.out.print((char)len);
        }
        fileReader.close();
    }
}

   字符数组读取

1
2
3
4
5
6
7
8
9
10
11
public class Demo {
    public static void main(String[] args) throws IOException{
        FileReader fileReader = new FileReader("d:\\aaa.txt");
        char[] b = new char[1024];
        int len = 0;
        while((len = fileReader.read(b))!=-1) {
            System.out.println(new String(b,0,len));
        }
        fileReader.close();
    }
}

3.传输数据

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class Demo {
    public static void main(String[] args){
        FileReader fileReader = null;
        FileWriter fileWriter = null;
        try {
            fileReader = new FileReader("d:\\aaa.txt");
            fileWriter = new FileWriter("d:\\bbb/txt");
            char[] ch = new char[1024];
            int len = 0;
            while((len=fileReader.read(ch))!=-1) {
                fileWriter.write(ch,0,len);
                fileWriter.flush();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(fileWriter!=null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(fileReader!=null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

 

posted @   CHAHN  阅读(115)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示