代码:
/** Java读取txt文件的内容,返回一个每行为一个String[]的ArrayList集合
* @param filePath 文件路径
* @param encoding 编码格式
* @return 每行为一个String[]的ArrayList集合
*/
public static ArrayList readTxtFile(String filePath,String encoding) {
ArrayList res = new ArrayList();
try {
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 编码格式必须和文件的一致
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
res.add(lineTxt.split("\t"));
}
read.close();
} else {
System.out.println("指定的文件不存在");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return res;
}
public static void main(String argv[]) {
String filePath = "d:\\信息\\ceshi.txt";
List<String> text=new ArrayList();
text=readTxtFile(filePath,"utf-8");
System.out.println(text);
}
txt文件内容
869002040031169
869608040194623
869608040390155
869608040042905
869608040482085
86209203009065
869608040136962
86209203003121
869608040095283
869608040489411
869608040175531
869608040167595
869608040100562
869608040302374
869608040051658
86209203007780
869608040509788
86209203009739
测试结果: