import cn.hutool.core.util.ObjectUtil;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @Description 文件读取
* @Author li.x
* @Date 2020/11/5 10:13
*/
public class FileReadUtils {
public static void main(String[] args) {
String path = "";
/* //读取全部内容
String allContent = FileReadUtils.readFile(path);
System.out.println(allContent);
System.out.println();
//跳过首几行
String skipStartcontent = FileReadUtils.readFile(path, 1);
System.out.println(skipStartcontent);
System.out.println();
//去掉尾几行
String skipStartAndEndcontent = FileReadUtils.readFile(path, 0, 1);
System.out.println(skipStartAndEndcontent);
System.out.println();*/
//截取中间端,去掉首尾几行
String content = FileReadUtils.readFile(path, 1, 1);
System.out.println(content);
}
/**
* @Description 读取文件全部内容
* @Author li.x
* @Param path:文件路径
* @Return
* @Date 2020/11/5 10:22
*/
public static String readFile(String path) {
return read(path, 0, 0);
}
/**
* @Description 读取文件全部内容
* @Author li.x
* @Param path:文件路径 skipStartIndex:跳过起始行数
* @Return
* @Date 2020/11/5 10:22
*/
public static String readFile(String path, Integer skipStartIndex) {
return read(path, skipStartIndex, 0);
}
/**
* @Description 文件读取实现,跳行截取中段。
* @Author li.x
* @Param path:文件路径 skipStartIndex:跳过行数 skipReciprocalIndex:截取到末尾倒数行数
* @Return
* @Date 2020/11/5 10:22
*/
public static String readFile(String path, Integer skipStartIndex, Integer skipReciprocalIndex) {
return read(path, skipStartIndex, skipReciprocalIndex);
}
/**
* @Description 文件读取实现,跳行截取中段。
* @Author li.x
* @Param path:文件路径 skipStartIndex:跳过行数 skipReciprocalIndex:截取到末尾倒数行数
* @Return
* @Date 2020/11/5 10:15
*/
private static String read(String path, Integer skipStartIndex, Integer skipReciprocalIndex) {
if (!new File(path).exists()) {
return null;
}
Stream<String> fileLines = null;
try {
if (ObjectUtil.isEmpty(skipStartIndex)) {
skipStartIndex = 0;
}
if (ObjectUtil.isEmpty(skipReciprocalIndex)) {
skipReciprocalIndex = 0;
}
fileLines = Files.lines(Paths.get(path)).skip(skipStartIndex);
String[] fileArr = fileLines.toArray(String[]::new);
Supplier<Stream<String>> streamSupplier = () -> Stream.of(fileArr);
return streamSupplier.get().limit(streamSupplier.get().count() - skipReciprocalIndex).collect(Collectors.joining());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileLines != null) {
fileLines.close();
}
}
return null;
}
}
基于lambda的文件读取工具类
最新推荐文章于 2022-11-14 09:12:01 发布