JAVA读写文件小实例

        测试同事在测试时,需要测试一些比较特殊的场景,需要往第三方的文件中新增数据,而第三方文件内容是以特殊的\u0001做为分隔符的,用普通的文本编辑工具打开是乱码。因此,特写了一个文件操作的小程序给测试同事。

        小程序功能:往第三方文件中新增数据,新增的数据是以“|”分隔的。当然,对readDataFromFile方法稍加修改,也可以从文件中读取数据。

FileUtils.java

package com.bijian.tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.google.common.base.Splitter;
import com.google.common.io.Closeables;

public class FileUtils {
    
    private final static String CHARACTER_ENCODING_UTF_8 = "UTF-8";
    private final static String SPLIT_CHAR = "\u0001";
    private final static String LOCAL_SPLIT_CHAR = "|";
    
    private final static String FILE_NAME_WITH_PATH = "D:\\data\\files\\test.txt";
    
    public static void main(String[] args) {
        
        List data = new ArrayList();
        data.add("123456789|201|301|20170124|153401");
        data.add("222222222|202|302|20170124|153501");
        
        List dataList = new ArrayList();
        
        for(String line : data) {
            parseLineAndAdd(line, dataList);
        }
        generateCompareFile(FILE_NAME_WITH_PATH, dataList);
    }

    /**
     * 从文件中读取数据
     * @return
     */
    private static List readDataFromFile() {
        
        List dataList = new ArrayList();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_NAME_WITH_PATH)));
            String lineStr;
            while ((lineStr = reader.readLine()) != null) {
                parseLineAndAdd(lineStr, dataList);
            }
        }catch(Exception e) {
            System.err.println("读取文件出错," + e);
        }finally {
            try {
                if(reader != null) {
                    Closeables.close(reader, false);
                }
            } catch (IOException e) {
                    reader = null;
            } finally {
                    reader = null;
            }
        }
        return dataList;
    }
    
    private static void parseLineAndAdd(String line, List dataList) {
        
        List lineData = Splitter.on(LOCAL_SPLIT_CHAR).splitToList(line);
        if (CollectionUtils.isNotEmpty(lineData)) {

            DataDto data = new DataDto();
            
            data.setId(lineData.get(0));
            data.setbCode(lineData.get(1));
            data.setcCode(lineData.get(2));
            data.setDate(lineData.get(3));
            data.setTime(lineData.get(4));

            dataList.add(data);
        }
    }
    
    /**
     * 根据指定的文件全路径创建空白文件
     */
    public static void createNewFile(String fileName) {
        String dir = fileName.substring(0, fileName.lastIndexOf(File.separator));
        File dirs = new File(dir);
        if (!dirs.exists()) {
            dirs.mkdirs();
        }

        if (!dirs.mkdirs() && !dirs.isDirectory()) {
            System.out.println((new StringBuilder("Unable to create directory ")).append(dirs).toString());
        }

        File file = new File(fileName);
        try {
            if(file.exists()){
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            System.out.println(new StringBuffer("Create File ").append(fileName).append(" happen error,reason:").append(e.toString()).toString());
        }
    }
    
    private static void generateCompareFile(String fileName, List dataList) {

        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true),
                    CHARACTER_ENCODING_UTF_8));
            System.out.println("文件写入开始");
            if (!(CollectionUtils.isEmpty(dataList))) {
                for (DataDto temp : dataList) {
                    writeCoreCompareFileToWriter(bufferedWriter, temp);
                }
            } else {
                System.out.println("无数据写入");
            }
            System.out.println("文件写入结束");
        } catch (Exception e) {
            System.err.println("文件写入过程出现异常:" + e);
        } finally {
            try {
                Closeables.close(bufferedWriter, false);
            } catch (IOException e) {
                System.err.println("关闭IO流失败" + e);
            } finally {
                bufferedWriter = null;
            }
        }
    }
    
    private static void writeCoreCompareFileToWriter(BufferedWriter bufferedWriter, DataDto data)
            throws Exception {
        
        StringBuilder line = new StringBuilder();
        
        line.append(StringUtils.defaultIfEmpty(data.getId(), "")).append(SPLIT_CHAR)
            .append(StringUtils.defaultIfEmpty(data.getbCode(), "")).append(SPLIT_CHAR)
            .append(StringUtils.defaultIfEmpty(data.getcCode(), "")).append(SPLIT_CHAR)
            .append(StringUtils.defaultIfEmpty(data.getDate(), "")).append(SPLIT_CHAR)
            .append(StringUtils.defaultIfEmpty(data.getTime(), "")).append(SPLIT_CHAR);
        
        bufferedWriter.write(line.toString());
        bufferedWriter.write("\n");
    }
}

DataDto.java

package com.bijian.tools;

public class DataDto {
    
    private String id;

    private String bCode;

    private String cCode;

    private String date;

    private String time;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getbCode() {
        return bCode;
    }

    public void setbCode(String bCode) {
        this.bCode = bCode;
    }

    public String getcCode() {
        return cCode;
    }

    public void setcCode(String cCode) {
        this.cCode = cCode;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

你可能感兴趣的:(java基础,java,FileUtils,FileInputStream)