java FileWriter和FileReader

来源:互联网 发布:台湾网络剧 编辑:程序博客网 时间:2024/05/21 08:01

第1章    FileWriter和FileReader

1.1    IO流概述和分类

l IO流用来处理设备之间的数据传输

n 文件复制(U盘拷贝)

n 上传文件(微信图片,QQ空间图片)

n 下载文件(迅雷)

l IO流分类

n 字符输出流

u FileWriter

n 字符输入流

u FileReader

l 图解

1.2    FileWriter

1.2.1   FileWriter写数据

l 构造方法

n FileWriter(String fileName) 传递一个文件名称

l 成员方法

n void write(String str) 往文件中写入一个字符串。

n void flush() 刷新该流的缓冲,把内存缓冲区中的数据刷新到文件中。

n void close() 关闭此流,但要先刷新它。

l 输出流写数据的步骤:

n 1.创建输出流对象

n 2.调用输出流对象的写数据的方法

n 3.释放资源

public classDemo01FileWriter {

    publicstaticvoidmain(String[] args) throws IOException {

        //创建输出流对象

        FileWriter fw= new FileWriter("d:\\a.txt");

        /*

         *创建输出流对象做了哪些事情:

         *     A:调用系统资源创建了一个文件

         *     B:创建输出流对象

         *     C:把输出流对象指向文件

         */

       

        //调用输出流对象的写数据的方法

        //写一个字符串数据

        fw.write("IO流你好");

        //数据没有直接写到文件,其实是写到了内存缓冲区

        fw.flush();

       

        //释放资源

        //通知系统释放和该文件相关的资源

        fw.close();

       

        //while(true){}

    }

}

1.2.2   路径问题

l 路径:

n 相对路径:相对当前项目而言的,在项目的根目录下(a.txt)

n 绝对路径:以盘符开始的路径(d:\\a.txt)

1.2.3   关闭和刷新方法的区别

l close()和flush()方法的区别:

n flush():刷新缓冲区。流对象还可以继续使用。

n close():先刷新缓冲区,然后通知系统释放资源。流对象不可以再被使用了。

public classDemo02FileWriter {

    publicstaticvoidmain(String[] args) throws IOException {

        //创建输出流对象

        //FileWriterfw = new FileWriter("d:\\a.txt");

        FileWriter fw= new FileWriter("a.txt");

       

        //调用输出流对象的写数据方法,并刷新缓冲区

        fw.write("helloworld");

        fw.flush();

        fw.write("java");

        fw.flush();

       

        //释放资源

        fw.close();

       

        //Streamclosed

        //fw.write("javaee");

        //fw.flush();

    }

}

1.2.4   写数据的5个方法

l void write(String str):写一个字符串数据

l void write(String str,intindex,int len):写一个字符串中的一部分数据, index:开始索引,len:写几个

l void write(int ch):写一个字符数据,这里写int类型的好处是既可以写char类型的数据,也可以写char对应的int类型的值。'a',97

l void write(char[] chs):写一个字符数组数据

l void write(char[] chs,intindex,int len):写一个字符数组的一部分数据, index:开始索引,len:写几个

public classDemo03FileWriter {

    publicstaticvoidmain(String[] args) throws IOException {

        //创建输出流对象

        FileWriter fw= new FileWriter("b.txt");

       

        //voidwrite(String str):写一个字符串数据

        fw.write("abcde");

       

        //voidwrite(String str,int index,int len):写一个字符串中的一部分数据, index:开始索引,len:写几个

        fw.write("abcde",0,5);

        fw.write("abcde",1,3);

       

        //voidwrite(int ch):写一个字符数据,这里写int类型的好处是既可以写char类型的数据,也可以写char对应的int类型的值。'a',97

        fw.write('a');

        fw.write(97);

       

        //voidwrite(char[] chs):写一个字符数组数据

        char[]chs = {'a','b','c','d','e'};

        //fw.write(chs);

       

        //voidwrite(char[] chs,int index,int len):写一个字符数组的一部分数据, index:开始索引,len:写几个

        fw.write(chs,0,5);

        fw.write(chs,2,3);

       

        //释放资源

        fw.close();

    }

}

1.2.5   换行写入

l 换行问题

n windows:\r\n

n linux:\n

n mac:\r

n 换行符可以写在第一个数据的结尾,也可以写在第二个数据的开头

1.2.6   追加写入

l 续写问题

n FileWriter(String fileName,boolean append)

n 构造放中参数的作用:

u 第一个参数:写入文件的目的地

u 第二个参数:append作用

                          true:可以续写

                          false:不能续写,覆盖之前的文件

1.3    FileReader

1.3.1   FileReader读数据

l 构造方法

n FileReader(String fileName) 传递要读取的文件名称

l 成员方法

n int read() 读取单个字符并返回

n int read(char[] cbuf) 一次读取一个字符数组的数据,返回的是实际读取的字符个数

l 输入流读文件的步骤:

n 1.创建输入流对象

n 2.调用输入流对象的读数据方法

n 3.释放资源

public classDemo01FileReader {

    publicstaticvoidmain(String[] args) throws IOException {

        //创建输入流对象

        //FileReaderfr = new FileReader("fr.txt");

        FileReader fr= new FileReader("Demo01FileWriter.java");

       

        //调用输入流对象的读数据方法

        //intread():一次读取一个字符

       

        intch;

        /*

         *while循环的条件表达式一共做了3件事情

         *  1:fr.read() 读取一个字符

         *  2:ch=fr.read() 把读取的字符赋值给ch

         *  3:ch != -1  判断ch是否为-1

         */

        while((ch=fr.read())!=-1){

            //System.out.println(ch);

            //System.out.println((char)ch);

            System.out.print((char)ch);

        }

       

        //释放资源

        fr.close();

    }

}

l 注意:如果构造方法中的文件不存在,会抛异常

n java.io.FileNotFoundException:fr.txt (系统找不到指定的文件。)

1.3.2   读取字符数组

l int read(char[] cbuf) 一次读取一个字符数组的数据,返回的是实际读取的字符个数

public classDemo02FileReader {

    publicstaticvoidmain(String[] args) throws IOException {

        //创建输入流对象

        //FileReaderfr = new FileReader("fr2.txt");

        FileReader fr= new FileReader("FileWriterDemo.java");

       

//调用输入流对象的读数据方法

        //int read(char[] cbuf):一次读取一个字符数组的数据,返回的是实际读取的字符个数

        char[]chs =newchar[1024];//这里可以是1024及其整数倍

        intlen;

        /* 

         *while循环的条件表达式一共做了3件事情

         *  1:fr.read(chs) 把数据读取到数组中

         *  2:len=fr.read(chs)把读取的有效个数赋值给len

         *  3:len != -1 判断读取的有效个数是否为-1

         */

        while((len=fr.read(chs))!=-1) {

            System.out.print(newString(chs,0,len));

        }

       

        //释放资源

        fr.close();

    }

}

1.3.3   -读取数据的两种方式图解

第2章    BufferedWriter和BufferedReader

2.1    字符缓冲流

2.1.1   基本用法

l BufferedWriter:将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。

l BufferedReader:从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。

public classDemo01BufferedStream {

    publicstaticvoidmain(String[] args) throws IOException {

        //创建输出缓冲流对象

        BufferedWriter bw= new BufferedWriter(new FileWriter("bw.txt"));

        bw.write("hello");

        //bw.flush();

        bw.close();

       

        //创建输入缓冲流对象

        BufferedReader br= new BufferedReader(new FileReader("bw.txt"));

       

        /*

        //一次读写一个字符

        int ch;

        while((ch=br.read())!=-1){

            System.out.print((char)ch);

        }

        */

       

        //一次读写一个字符数组

        char[]chs =newchar[1024];

        intlen;

        while((len=br.read(chs))!=-1) {

            System.out.print(newString(chs,0,len));

        }

       

        //释放资源

        br.close();

    }

}

2.1.2    缓冲流的特殊功能

l BufferedWriter

n void newLine():写一个换行符,这个换行符由系统决定

l BufferedReader

n String readLine():一次读取一行数据,但是不读取换行符

public classDemo03BufferedStream {

    publicstaticvoidmain(String[] args) throws IOException {

        BufferedWriter bw= new BufferedWriter(new FileWriter("bw2.txt"));

        for(intx=0; x<10; x++) {

            bw.write("hello"+x);

            //bw.write("\r\n");

            bw.newLine();

            bw.flush();

        }

        bw.close();

       

        BufferedReader br= new BufferedReader(new FileReader("br.txt"));

        String line;

        /*

         *while循环的条件表达式一共做了3件事情

         *  1:br.readLine() 读取一行

         *  2:line=br.readLine() 把读取的一行字符串赋值给line

         *  3:line != null 判断line是否为null

         */

        while((line=br.readLine())!=null) {

            System.out.println(line);

        }

        br.close();

    }

}

2.2    IO流练习

2.2.1   从集合到文件

n 把ArrayList集合中的字符串数据存储到文本文件

n 每一个字符串元素作为文件中的一行数据

public classDemo02ArrayListToFileTest {

    publicstaticvoidmain(String[] args) throws IOException {

        //创建集合对象

        ArrayList<String> list = newArrayList<String>();

       

        //往集合中添加字符串元素

        list.add("hello");

        list.add("world");

        list.add("java");

       

        //创建输出缓冲流对象

        BufferedWriter bw= new BufferedWriter(new FileWriter("array.txt"));

       

        //遍历集合,得到每一个字符串元素,然后把该字符串元素作为数据写到文本文件

        for(inti=0; i<list.size();i++) {

            String s= list.get(i);

            bw.write(s);

            bw.newLine();

            bw.flush();

        }

       

        //释放资源

        bw.close();

    }

}

2.2.2   从文件到集合

n 从文本文件中读取数据到ArrayList集合中,并遍历集合

n 每一行数据作为一个字符串元素

public classDemo03FileToArrayListTest {

    publicstaticvoidmain(String[] args) throws IOException {

        //创建输入缓冲流对象

        BufferedReader br=

new BufferedReader(new FileReader("array.txt"));

       

        //创建集合对象

        ArrayList<String>list = newArrayList<String>();

       

        //读取数据,每次读取一行数据,把该行数据作为一个元素存储到集合中

        String line;

        while((line=br.readLine())!=null) {

            list.add(line);

        }

       

        //释放资源

        br.close();

       

        //遍历集合

        for(inti=0; i<list.size();i++) {

            String s= list.get(i);

            System.out.println(s);

        }

    }

}

 

2.2.3   反转唐诗

n 把文本中的唐诗恢复顺序(文本中为行倒序的唐诗) 每行倒序

n 分析: 文本中的唐诗每行读取出来才存储到集合中,在对集合反向遍历,遍历后的内容写到新的文件中

public static void main(String[] args) throwsIOException{

        //字符输入流读取存储唐诗的文本文件

        FileReaderfr = new FileReader("c:\\1.txt");

        //字符输入流缓冲流,按行读取

        BufferedReaderbr = new BufferedReader(fr);

        //集合对象,存读取到的唐诗

        ArrayList<String>list = new ArrayList<String>();

        Stringline = null;

        while((line= bfr.readLine())!=null){

            //读取每行唐诗存储集合

            list.add(line);

        }

        //字符输出流,将唐诗写入文本

        FileWriterfw = new FileWriter("c:\\2.txt");

        //字符输入缓冲流,换行写入

        BufferedWriterbw = new BufferedWriter(fw);

        //集合倒序遍历,索引最大值开始,0结束

        for(intx = list.size()-1; x >= 0 ; x--){

            bfw.write(list.get(x));

            bfw.newLine();

            bfw.flush();

        }

        bfw.close();

        bfr.close();

    }

2.2.4   把集合中的自定义对象写入到文件中

public static void main(String[] args)throws IOException{

        //创建集合对象,存储Student对象

        ArrayList<Student>array = newArrayList<Student>();

        //创建3个学生对象

        Students1 = newStudent("张三","18");

        Students2 = newStudent("李四","20");

        Students3 = newStudent("王武","19");

        //对学生对象存储到集合

        array.add(s1);

        array.add(s2);

        array.add(s3);

        FileWriterfw = newFileWriter("c:\\student.txt");

        BufferedWriterbfw = newBufferedWriter(fw);

        for(intx = 0 ;x< array.size();x++){

            //获取集合中的Student对象

            Students = array.get(x);

            //Student对象get方法,将姓名年龄写入文本

            bfw.write(s.getName()+" "+s.getAge());

            bfw.newLine();

            bfw.flush();

        }

        bfw.close();

    }

2.2.5   把文件中的数据读取出来,封装成自定义对象存储到集合中

  publicstaticvoid main(String[] args) throwsIOException{

        //创建集合对象,存储Student对象

        ArrayList<Student> array = newArrayList<Student>();

        FileReader fr = new FileReader("c:\\student.txt");

        //字符输入流缓冲流,按行读取文件

        BufferedReader bfr = new BufferedReader(fr);

        String line =null;

        while((line =bfr.readLine())!=null){

            //读取每行,空格切割字符串

            String[] str = line.split(" ");

            Student s = new Student();

            //Student对象name属性值为数组0索引

            s.setName(str[0]);

            //Student对象age属性值为数组1索引

            s.setAge(str[1]);

            //Student对象存储到集合

            array.add(s);

        }

        for(intx = 0 ;x < array.size();x++){

            Student s = array.get(x);

            System.out.println(s.getName()+" "+s.getAge());

        }

        bfr.close();

    }

 

原创粉丝点击