public static List read(String filePath){
BufferedReader br = null;
List<String> strings = new ArrayList();
String line = null;
try {
//根据文件路径创建缓冲输入流
br = new BufferedReader(new FileReader(filePath));
String str = "";
//循环读取文件的每一行,对需要修改的行进行修改,放入缓冲对象中
while ((line = br.readLine()) != null) {
//设置正则将多余空格都转为一个空格
str = line;
strings.add(str);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (br != null) {// 关闭流
try {
br.close();
} catch (IOException e) {
br = null;
}
}
}
return strings;
}
测试:
public class Test {
public static void main(String[] args) {
//读入文件
String filePath = "xxx.txt"; // 文件路径
List<String> lists = read(filePath);
System.out.println(lists);
}
}