码迷,mamicode.com
首页 > 编程语言 > 详细

Java读取文件

时间:2015-07-31 14:41:54      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

用惯了python在使用java,在读取文件这真心觉得麻烦,写了一小段代码对java的读写进行了简单的封装,总算舒服了一点:

技术分享
package seleniumTest;

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

import java.util.List;
import java.util.ArrayList;

public class MyFile {
    public File f;
    public FileWriter fw;
    public FileReader fr;
    MyFile(String path){
        f = new File(path);
        if(f.exists() != true){
            try{
                f.createNewFile();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        this.createWriter();
        this.createReader();
    }
    
    private void createWriter(){
        try {
            fw = new FileWriter(f, true);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    private void createReader(){
        try {
            fr = new FileReader(f);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public FileWriter getWriter(){
        return fw;
    }
    
    public BufferedReader getReader(){
        BufferedReader br = new BufferedReader(fr);
        return br;
    }
    
    public static void appendWriter(String path, List<String> lines){
        MyFile tmp = new MyFile(path);
        tmp.createWriter();
        FileWriter fw = tmp.getWriter();
        for(String line: lines){
            try {
                fw.write(String.format("%s%s", line.trim(), "\r\n"));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            fw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static List<String> myReader(String path){
        List<String> result = new ArrayList<String>();
        MyFile tmp = new MyFile(path);
        tmp.createWriter();
        BufferedReader fr = tmp.getReader();
        String s;
        try {
            while((s = fr.readLine()) != null){
                result.add(s);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
}
View Code

 

Java读取文件

标签:

原文地址:http://www.cnblogs.com/sudz/p/4691897.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!