import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* @Description : 文本文件处理类
* @Date : 2019/9/19
* @Author :
*/
@Slf4j
public class TxtUtils {
/**
* <p>
* 读取文本文件到字符串中。
* 建议把UTF-8提取出来,当成一个常量,而不用魔法值。
* </p>
* @param fileName 需要保证文件可读取,内容在2147483647字数以内
* @return
*/
public static String readToString(String fileName) {
File file = new File(fileName);
Long fileLength = file.length();
byte[] fileContent = new byte[fileLength.intValue()];
try (FileInputStream in = new FileInputStream(file)){
in.read(fileContent);
} catch (FileNotFoundException e) {
log.error("{TxtUtils#readToString} file not found");
} catch (IOException e) {
log.error("{TxtUtils#readToString} IOException");
}
try {
return new String(fileContent, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error("{TxtUtils#readToString} The OS does not support " + "UTF-8");
}
return null;
}
}
UTF-8
StandardCharsets.UTF_8
这个类的常量就可以用了~没必要在定义一遍
有时候,可能对文件txt文本使用notepad++之类的转换成UTF-8。
否则中文编码有时候会乱