美文网首页
IO流学习总结-字符流

IO流学习总结-字符流

作者: 秃头大叔 | 来源:发表于2017-11-15 18:14 被阅读0次

字符流

复制文件1

通过FileReader和FileWriter实现;


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

public class copyfile {
    public static void main(String[] args) {
        FileWriter fw = null;
        FileReader fr = null;
        try {
            fw = new FileWriter("copyfile.txt");
            fr = new FileReader("test.text");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        char [] arr = new char[1024];
        int num = 0;
        
        try {
            while((num = fr.read(arr)) != -1){
                fw.write(new String(arr,0,num));
                fw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

复制文件2

通过缓冲区BufferedReader和BufferedWriter实现;

package io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class bufferecopyfileagain {

    /**
     * @param args
     */
    public static void main(String[] args) {
        FileWriter fw = null;
        FileReader fr =null;
        BufferedReader bufr = null;
        BufferedWriter bufw = null;
        try {
            fw = new FileWriter("copyfile13.txt");
            fr = new FileReader("copyfile11.txt");
            bufr = new BufferedReader(fr);
            bufw = new BufferedWriter(fw);
            String line = null;
            while((line = bufr.readLine()) != null){   //缓冲区实现了读行方法
                bufw.write(line);
                bufw.flush();        //强制刷新,写入文件
                bufw.newLine();   //换行
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.toString());
        }
        finally {
            try {
                bufw.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        
    }

}

内容无太多备注,仅仅用来快速回忆知识点,毕竟自学的路相对漫长,前端的工作还是要继续滴;

相关文章

网友评论

      本文标题:IO流学习总结-字符流

      本文链接:https://www.haomeiwen.com/subject/chyhvxtx.html