java读取本地txt文件内容
假设需要读取如下内容的文件,中间用\t(制表符)来分割
--ID 数据 15072 1 3 5 20 21 31 5 15073 1 2 17 22 26 27 4 15074 4 7 21 25 26 29 8 15075 6 11 13 19 21 32 4 15076 1 9 10 19 23 27 9 15077 1 6 8 10 13 27 16 15078 3 7 20 22 26 29 2 15079 9 14 15 20 26 32 11 15080 14 17 25 27 28 30 2 15081 13 20 22 26 28 31 13 15082 2 8 9 14 28 30 7 15083 6 7 16 18 29 32 5 15084 15 18 20 22 28 29 15 15085 2 8 25 27 28 29 5
--开头的自动忽略,返回一个每行为一个String[]的ArrayList集合
使用text.get(0)[0]来获取目标字段
package tool; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class ReadTextByFile { /** Java读取txt文件的内容,--开头的自动忽略,返回一个每行为一个String[]的ArrayList集合 * @param filePath 文件路径 * @param encoding 编码格式 * @return 每行为一个String[]的ArrayList集合 */ public static ArrayList<String[]> readTxtFile(String filePath,String encoding) { ArrayList<String[]> res = new ArrayList<String[]>(); 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) { if (!lineTxt.startsWith("--")) { 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:\\his.txt"; ArrayList<String[]> text=new ArrayList<String[]>(); text=readTxtFile(filePath,"utf-8"); System.out.println(text.get(0)[0]); } }