import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; /** * 读取txt文件的行 * */ public class FileUtil { /** * java.nio.file.Files方式 * @param filePath * @return */ public static List<String> parseFileContext(String filePath) { System.out.println("filePath="+filePath); List<String> dataArray = null; try { dataArray = Files.readAllLines(Paths.get(filePath)); } catch (IOException e) { e.printStackTrace(); } return dataArray; } /** * 流方式 * @param filePath * @return */ public static List<String> oldParseFileContext(String filePath) { System.out.println("filePath="+filePath); List<String> dataArray = new ArrayList<String>(); FileInputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; // 用于包装InputStreamReader,提高处理性能。因为BufferedReader有缓冲的,而InputStreamReader没有。 try { String str = ""; fis = new FileInputStream(filePath);// FileInputStream isr = new InputStreamReader(fis); br = new BufferedReader(isr); while ((str = br.readLine()) != null) { dataArray.add(str); } } catch (Exception e) { e.printStackTrace(); } finally { try { br.close(); isr.close(); fis.close(); } catch (Exception e2) { e2.printStackTrace(); } } return dataArray; } public static void main(String[] args) { String path = "E:\test.txt"; // List<String> lst = parseFileContext(path); List<String> lst = oldParseFileContext(path); for (String string : lst) { System.out.println("string="+string); } } }