对于内容较少的文本,可以直接使用;如果文本内容多,行数大,不建议直接操作文本。
package cnki.tpi.utils;
import cn.hutool.core.io.FileUtil;
import cnki.tpi.util.SystemProperties;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* ClassName: FileLineUtil
* Description:
*
* @author 小黄
* date: 2020/8/18 14:35
*/
public class FileLineUtil {
/**
* 读取文件指定行数(读取一行)
* @param filePath
* @param lineNumber
*/
public static String getStrByLineNum(String filePath,int lineNumber){
String appointedLine = "";
FileInputStream fis = null;
InputStreamReader in = null;
LineNumberReader reader = null;
try {
fis =new FileInputStream(filePath);
in =new InputStreamReader(fis, "UTF-8");
reader = new LineNumberReader(in);
long totalLine = getTotalLine(filePath);
if(lineNumber < 0 || lineNumber > totalLine){
return "";
}
int line = 1;
reader.setLineNumber(lineNumber);
long i = reader.getLineNumber();
String s = "";
while((s = reader.readLine()) != null){
if(i == line){
appointedLine = s;
break;
}
line++;
}
return appointedLine;
} catch (Exception e) {
e.printStackTrace();
}