Java读取txt格式工具类

读取txt内容到bean对象,可自定义字段分隔符,读取时会过滤掉第一行内容。

txt文件:
在这里插入图片描述
java读取后:
在这里插入图片描述

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * TXT文本读取
 *
 * @author ukou
 * @date 2022/04/01
 */
public class ReadTxtUtil {

    private ReadTxtUtil() {
    }

    public static final String DEFAULT_CHARSET = "\t";
    public static final String GBK = "GBK";
    public static final String UTF_8 = "UTF-8";
    public static final String UTF_16 = "UTF-16";
    public static final String UNICODE = "Unicode";
    public static final String HTTP = "http";

    public static StringBuilder readTxtFile(String filePath) throws IOException {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = getInputStream(filePath);
        if (inputStream == null) {
            return sb;
        }
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, resolveCharset(filePath));
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String text;
        // 使用readLine方法,一次读一行
        while ((text = bufferedReader.readLine()) != null) {
            sb.append(text).append(System.lineSeparator());
        }
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        return sb;
    }

    public static String readTxtFileString(String filePath) { //优化读取txt工具,防止io阻塞
        String content = null;
        try (Reader reader = new InputStreamReader(new FileInputStream(filePath), resolveCharset(filePath))) {
            StringBuilder sb = new StringBuilder();
            char[] tempchars = new char[1024];
            while (reader.read(tempchars) != -1) {
                sb.append(tempchars);
            }
            content = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    public static <T> List<T> readTxtFile(String filePath, Class<T> clazz) throws Exception {
        return readTxtFile(filePath, clazz, DEFAULT_CHARSET);
    }

    public static <T> List<T> readTxtFile(String filePath, Class<T> clazz, String separator) throws Exception {
        return readTxtFile(getInputStream(filePath), clazz, separator, resolveCharset(filePath));
    }

    public static <T> List<T> readTxtFile(InputStream inputStream, Class<T> clazz) throws Exception {
        return readTxtFile(inputStream, clazz, DEFAULT_CHARSET);
    }

    public static <T> List<T> readTxtFile(InputStream inputStream, Class<T> clazz, String separator) throws Exception  {
        String charset = resolveCharset(inputStream);
        return readTxtFile(inputStream, clazz, separator, charset);
    }

    public static <T> List<T> readTxtFile(InputStream inputStream, Class<T> clazz, String separator, String charset) throws Exception {
        List<T> list = new ArrayList<>();
        if (inputStream == null) {
            return list;
        }
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String text;
        int line = 0;
        // 使用readLine方法,一次读一行
        while ((text = bufferedReader.readLine()) != null) {
            if (line > 0) {
                String[] split = text.split(separator);
                T t = clazz.getDeclaredConstructor().newInstance();
                Field[] declaredFields = t.getClass().getDeclaredFields();
                for (int i = 0; i < split.length; i++) {
                    declaredFields[i].setAccessible(true);
                    declaredFields[i].set(t, split[i]);
                }
                list.add(t);
            }
            line++;
        }
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        return list;
    }

    // 获取txt文件编码
    public static String resolveCharset(String filePath) {
        return resolveCharset(getInputStream(filePath));
    }

    // 获取txt文件编码
    public static String resolveCharset(InputStream inputStream) {
        if (inputStream == null) {
            return GBK;
        }
        byte[] head = new byte[3];
        try {
            inputStream.read(head);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (head[0] == -1 && head[1] == -2 ) {
            return UTF_16;
        } else if (head[0] == -2 && head[1] == -1 ) {
            return UNICODE;
        } else if(head[0] == -17 && head[1] == -69 && head[2] == -65) {
            return UTF_8;
        }
        return GBK;
    }

    public static InputStream getInputStream(String filePath) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        // 区分本地文件和本地文件
        if (filePath.contains(HTTP)) {
            //oss
            try {
                return new URL(filePath).openStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            // 本地文件上传测试
            try {
                return new FileInputStream(filePath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值