文件读写

自己写的文件读写类,写文件是直接在文件后面添加内容,且一行一行的添加。

public class FileRW {   

    private File file;   
    private FileReader fileReader;   
    private BufferedReader br;   
    private FileWriter fileWriter;   
    private BufferedWriter bw;   

    public FileRW(String path){   
        this.file=new File(path);   
        initBufferReader();   
    }   

    public FileRW(File file){   
        this.file=file;   
        initBufferReader();   
    }   

    private void initBufferReader(){   
        try {   
            this.fileReader=new FileReader(file);   
            this.br=new BufferedReader(this.fileReader);   
            this.fileWriter=new FileWriter(file,true);//true表示在文件后面追加,而不是清空文件内容  
            this.bw=new BufferedWriter(fileWriter);   

        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   

    public String readline(){   
        try {   
            return br.readLine();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
        return null;   
    }   

    public void readClose(){   
        try {   
            br.close();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
    }   

    public void writeClose(){   
        try {   
            bw.flush();   
            bw.close();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
    }   

    public void write(String content){   
        try {   
            bw.write(content);   
            bw.newLine();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
    }   

    public void fileClose(){   
        try {   
            this.readClose();   
            this.writeClose();   
            this.fileReader.close();   
            this.fileWriter.close();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }          
    }   

}  
posted @ 2016-05-02 19:10  黄大仙爱编程  阅读(85)  评论(0编辑  收藏  举报