读取文本文件工具类
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 然后解析它即可