读取文本文件工具类

读取文本文件工具类

1.工具类ReadTxtUtil

package com.safesoft.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 读取文本文件工具类
 */
public class ReadTxtUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReadTxtUtil.class);

    private ReadTxtUtil() {
        // default implementation ignored
    }

    /**
     * 功能:Java读取txt文件的内容
     * 步骤:1:先获得文件句柄
     * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
     * 3:读取到输入流后,需要读取生成字节流
     * 4:一行一行的输出。readline()。
     * 备注:需要考虑的是异常情况
     *
     * @param filePath
     */

    private static final String FIND_DOCUMENT_EMPTY = "找不到指定文件夹";
    private static final String EXCEPTION_MSG = "读取文件内容出错";

    public static StringBuilder readTxtFile(String filePath) {
        StringBuilder readTxt = new StringBuilder();
        try {
            //String encoding = "UTF-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                judgeDocumentStepOne(file, readTxt);
            } else {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(FIND_DOCUMENT_EMPTY);
                }
            }
        } catch (Exception e) {
            LOGGER.error("异常:{}", EXCEPTION_MSG + e.getMessage());
        }
        return readTxt;

    }

    /**
     * 判断文件是否存在(第一步)
     *
     * @param file    文件
     * @param readTxt 读取内容
     * @throws IOException
     */
    private static void judgeDocumentStepOne(File file, StringBuilder readTxt) throws IOException {
        try {
            judgeDocumentStepTwo(file, readTxt);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }

    /**
     *
     */
    private static void judgeDocumentStepTwo(File file, StringBuilder readTxt) throws IOException {
        final FileInputStream fileInputStream = new FileInputStream(file);
        InputStreamReader read = new InputStreamReader(new FileInputStream(file));
        //考虑到编码格式
        try (BufferedReader bufferedReader = new BufferedReader(read)) {
            String lineTxt;
            while ((lineTxt = bufferedReader.readLine()) != null) {
                readTxt.append(lineTxt).append(";");
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        } finally {
            fileInputStream.close();
        }
    }


}

2.我们可以在这个工具类写一个main测试一下

(什么样的文件都可以读取,例如txt、properties等等 只不过有的读比如xlsx可能会乱码罢了)

public static void main(String[] args) {
    readBusLine();
}

public static void readBusLine() {
    String basePath = System.getProperty("user.dir"); // 获取项目根目录
    String fileName = basePath + "/src/main/resources/2023-07-11 04.log";
    StringBuilder stringBuilder = ReadTxtUtil.readTxtFile(fileName);
    String busLineInfo = stringBuilder.toString();
    String[] arr = busLineInfo.split(";");
    for (String bus : arr) {
        //String busLine = bus.substring(bus.indexOf("=====") + 5, bus.length());
        System.out.println(bus);
    }
}


//解析 fileName主要是获取文件的路径,我假设在resources放了一个2023-07-11 04.log文件 
//然后调用工具类  ReadTxtUtil.readTxtFile(fileName) 传路径  就获取stringBuilder 然后解析它即可
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值