写文件的工具类,输出有格式的文件(txt、json/csv)

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;

/**
 * 写文件的工具类,输出有格式的文件
 * 
 * |- TXT
 * |- JSON
 * |- CSV
 */
public class FileWriteUtil {

    // 缓冲区大小
    private final static int buffer_size = 1024;

    // 日志格式工具
    private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    // 小数的格式化工具,设置最大小数位为10
    private final static NumberFormat numFormatter = NumberFormat.getNumberInstance();
    static {
        numFormatter.setMaximumFractionDigits(10);
    }

    // 换行符
    @SuppressWarnings("restriction")
    private final static String lineSeparator = java.security.AccessController
            .doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));

    /**
     * 以指定编码格式写入多行多列到TXT文件
     * 
     * @param rows                要输出的数据
     * @param filePath            TXT文件的具体路径
     * @param charsetName        UTF-8
     * @throws Exception
     */
    public static void writeRows2TxtFile(List<Object[]> rows, String filePath, String charsetName) throws Exception {
        // TXT内容
        StringBuffer txtStr = new StringBuffer();

        // 拼接每一行
        for (int i = 0; i < rows.size(); i++) {
            // 拼接一行数据成字符串
            StringBuffer line = new StringBuffer();

            Object[] row = rows.get(i);
            for (int j = 0; j < row.length; j++) {
                String field = FileWriteUtil.formatField(row[j]);

                if (j == row.length - 1)
                    line.append(field);
                else
                    line.append(field).append("\t");
            }

            // 将一行数据的字符串添加到结果集中
            if (i == rows.size() - 1) { // 最后一行,不用换行
                txtStr.append(line);
            } else {
                txtStr.append(line).append(lineSeparator);
            }
        }

        // 将拼接后的完整内容写入文件
        FileWriteUtil.writeString2SimpleFile(txtStr.toString(), filePath, charsetName);
    }

    /**
     * 以指定编码格式写入多行多列到CSV文件
     * 
     * @param rows                要输出的数据
     * @param filePath            CSV文件的具体路径
     * @param charsetName        GB2312
     * @throws Exception
     */
    public static void writeRows2CsvFile(List<Object[]> rows, String filePath, String charsetName) throws Exception {
        // CSV内容
        StringBuffer csvStr = new StringBuffer();

        // 拼接每一行
        for (int i = 0; i < rows.size(); i++) {
            // 拼接一行数据成字符串
            StringBuffer line = new StringBuffer();

            Object[] row = rows.get(i);
            for (int j = 0; j < row.length; j++) {
                String field = FileWriteUtil.formatField(row[j]);

                if (j == row.length - 1)
                    line.append(String.format("\"%s\"", field));
                else
                    line.append(String.format("\"%s\",", field));
            }

            // 将一行数据的字符串添加到结果集中
            if (i == rows.size() - 1) { // 最后一行,不用换行
                csvStr.append(line);
            } else {
                csvStr.append(line).append(lineSeparator);
            }
        }

        // 将拼接后的完整内容写入文件
        FileWriteUtil.writeString2SimpleFile(csvStr.toString(), filePath, charsetName);
    }

    /**
     * 以指定编码格式写入JSON字符串到JSON文件
     * 
     * @param jsonStr        要输出的JSON字符串
     * @param filePath        JSON文件的具体路径
     * @param charsetName    UTF-8
     * @throws Exception
     */
    public static void writeJsonStr2JsonFile(String jsonStr, String filePath, String charsetName) throws Exception {
        // JSON字符串格式化
        jsonStr = JsonFormat.formatJson(jsonStr);

        // 将格式化后的JSON字符串以指定编码写入文件
        FileWriteUtil.writeString2SimpleFile(jsonStr, filePath, charsetName);

    }

    /**
     * 以指定编码格式写入字符串到CSV文件
     * 
     * @param csvStr        要输出的字符串(有CSV格式)
     * @param filePath        CSV文件的具体路径
     * @param charsetName    GB2312
     * @throws Exception
     */
    public static void writeCsvStr2CsvFile(String csvStr, String filePath, String charsetName) throws Exception {
        FileWriteUtil.writeString2SimpleFile(csvStr, filePath, charsetName);
    }

    /**
     * 以指定编码格式写入字符串到简单文件
     * 
     * @param str            要输出的字符串
     * @param filePath        简单文件的具体路径
     * @param charsetName    UTF-8 | GB2312
     * @throws Exception
     */
    public static void writeString2SimpleFile(String str, String filePath, String charsetName) throws Exception {

        BufferedWriter out = null;
        try {
            File file = new File(filePath);

            createNewFileIfNotExists(file);

            OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file), charsetName);
            out = new BufferedWriter(os, FileWriteUtil.buffer_size);

            out.write(str);

            out.flush();
        } finally {
            FileWriteUtil.close(out);
        }

    }

    /**
     * 格式化一个field成标准格式字符串 
     * 
     * 支持接收的参数类型(8中基本类型及包装类、String、Date)
     * 其他引用类型返回JSON字符串
     */
    private static String formatField(Object field) {
        // null时给一个空格占位
        if (null == field) {
            return " ";
        }

        @SuppressWarnings("rawtypes")
        Class clazz = field.getClass();

        // byte、short、integer、long
        if (clazz == byte.class || clazz == short.class || clazz == int.class || clazz == long.class
                || clazz == Byte.class || clazz == Short.class || clazz == Integer.class || clazz == Long.class) {
            return String.valueOf(field);
        }

        // float、double
        if (clazz == float.class || clazz == double.class || clazz == Float.class || clazz == Double.class) {
            return numFormatter.format(field);
        }

        // boolean、char、String
        if (clazz == boolean.class || clazz == Boolean.class || clazz == char.class || clazz == Character.class
                || clazz == String.class) {
            return String.valueOf(field);
        }

        // Date
        if (clazz == Date.class) {
            return dateFormat.format(field);
        }

        return JSON.toJSONString(field);
    }

    /**
     * 如果文件不存在,创建一个新文件
     */
    private static void createNewFileIfNotExists(File file) throws IOException {
        if (!file.exists()) {
            // 创建目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            // 创建文件
            file.createNewFile();
        }
    }

    /**
     * 关闭输出流
     */
    private static void close(Writer out) {
        if (null != out) {
            try {
                out.close();
            } catch (IOException e) {
                // e.printStackTrace();
            }
        }
    }

    /**
     * JSON字符串的格式化工具
     */
    static class JsonFormat {

        // 返回格式化JSON字符串。
        public static String formatJson(String json) {
            StringBuffer result = new StringBuffer();

            int length = json.length();
            int number = 0;
            char key = 0;

            for (int i = 0; i < length; i++) {
                key = json.charAt(i);

                if ((key == '[') || (key == '{')) {
                    if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
                        result.append('\n');
                        result.append(indent(number));
                    }

                    result.append(key);

                    result.append('\n');

                    number++;
                    result.append(indent(number));

                    continue;
                }

                if ((key == ']') || (key == '}')) {
                    result.append('\n');

                    number--;
                    result.append(indent(number));

                    result.append(key);

                    if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
                        result.append('\n');
                    }

                    continue;
                }

                if ((key == ',')) {
                    result.append(key);
                    result.append('\n');
                    result.append(indent(number));
                    continue;
                }

                result.append(key);
            }

            return result.toString();
        }

        // 单位缩进字符串,3个空格。
        private static String SPACE = "   ";

        // 返回指定次数(number)的缩进字符串。每一次缩进一个单个的SPACE。
        private static String indent(int number) {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < number; i++) {
                result.append(SPACE);
            }
            return result.toString();
        }
    }
}

 

posted @ 2018-05-29 16:52  迷失之路  阅读(1155)  评论(0编辑  收藏  举报