试着用nio读取txt
Path novelPath=Paths.get("C://txt/" filename); List<String> novellines=Files.readAllLines(novelPath);
报错
Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 1
查了下异常说明,是当输入字节序列对于给定 charset 来说是不合法的,或者输入字符序列不是合法的 16 位 Unicode 序列时,抛出此经过检查的异常
想到txt的编码应该是默认的gbk,点开readAllLines方法,显示用的是utf-8读取的
public static List<String> readAllLines(Path path) throws IOException { return readAllLines(path, StandardCharsets.UTF_8); }
改成gbk试试
Path novelPath=Paths.get("C://txt/" filename); Charset charset= Charset.forName("GBK"); List<String> novellines=Files.readAllLines(novelPath,charset);
成功